1. 程式人生 > >java 遞歸實現平衡二叉樹

java 遞歸實現平衡二叉樹

bsp get 實現 urn ole lean left current this

public class 平衡二叉樹
{
public class TreeNode
{
TreeNode left;
TreeNode right;
int val;

TreeNode(int x)
{
this.val = x;
}
}

// 獲取深度
private int getDepth(TreeNode tree, int currentDepth)
{
if (tree == null)
{
return currentDepth;
}
return Math.max(getDepth(tree.left, currentDepth + 1),
getDepth(tree.right, currentDepth + 1));

}

// 采用遞歸解決
public boolean isBalanced(TreeNode root)
{
if (root == null)
{
return true;
}
int depthOfLeft = getDepth(root.left, 1);
int depthOfRight = getDepth(root.right, 1);
if (Math.abs(depthOfLeft - depthOfRight) > 1)
{
return false;
}
else
{
return isBalanced(root.left) && isBalanced(root.right);
}
}
}

java 遞歸實現平衡二叉樹