检查二叉树是否平衡
Checking if a Binary Tree is Balanced
我在一本书上看到这个问题(Cracking the Coding Interview)。
建议的代码是:
public boolean isBalanced(Node root) {
if(root == null)
return true;
int leftHeight = getHeight(root.left);
System.out.println("left height: " + leftHeight);
int rightHeight = getHeight(root.right);
System.out.println("right height: " + rightHeight);
int diff = Math.abs(leftHeight - rightHeight);
// check if difference in height is more than 1
if (diff > 1)
return false;
// check if left and right subtrees are balanced
else
return isBalanced(root.left) && isBalanced(root.right);
我不明白的部分是为什么我们需要 return isBalanced(root.left) && isBalanced(root.right)。仅仅检查高度和 return 如果高度大于 1 则为 false,否则为 true 还不够吗?
不,仅检查高度是不够的,return如果高度大于 1,则为 false,否则为 true。简单地检查根的高度会导致如下误报:
A
/ \
B F
/ /
C G
/ /
D H
/ /
E I
我在一本书上看到这个问题(Cracking the Coding Interview)。 建议的代码是:
public boolean isBalanced(Node root) {
if(root == null)
return true;
int leftHeight = getHeight(root.left);
System.out.println("left height: " + leftHeight);
int rightHeight = getHeight(root.right);
System.out.println("right height: " + rightHeight);
int diff = Math.abs(leftHeight - rightHeight);
// check if difference in height is more than 1
if (diff > 1)
return false;
// check if left and right subtrees are balanced
else
return isBalanced(root.left) && isBalanced(root.right);
我不明白的部分是为什么我们需要 return isBalanced(root.left) && isBalanced(root.right)。仅仅检查高度和 return 如果高度大于 1 则为 false,否则为 true 还不够吗?
不,仅检查高度是不够的,return如果高度大于 1,则为 false,否则为 true。简单地检查根的高度会导致如下误报:
A
/ \
B F
/ /
C G
/ /
D H
/ /
E I