检查二叉树是否平衡

Sta*_*ime 2 java binary-tree

我在一本书中看到了这个问题(破解编码面试)。建议的代码是:

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);
Run Code Online (Sandbox Code Playgroud)

我不明白的部分是为什么我们需要返回isBalanced(root.left)&& isBalanced(root.right)。仅检查高度并在高度大于1时返回false,否则返回true是否足够?

Joh*_*pit 5

不,仅检查高度并返回false,如果高度大于1是不够的,否则返回true。只需检查根的高度,将导致如下所示的误报:

        A
       / \
      B   F
     /   /
    C   G
   /   /
  D   H
 /   /
E   I
Run Code Online (Sandbox Code Playgroud)