简体   繁体   中英

Checking if a Binary Tree is Balanced

I saw the question in a book (Cracking the Coding Interview). The suggested code is:

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);

The part I don't understand is why do we need return isBalanced(root.left) && isBalanced(root.right). Isn't it enough just to check the height and return false if the hight is more than 1, and true otherwise?

No, it is not enough to just to check the height and return false if the height is more than 1, and true otherwise . Simply checking the root's height would result in false positives like the following:

        A
       / \
      B   F
     /   /
    C   G
   /   /
  D   H
 /   /
E   I

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM