Checking if a binary tree is balanced
Your question is unclear, though I can tell that your code is broken.

Your code here:


  public static boolean isBalanced(BinaryTreeNode n) {
    // if height = (|hl - hr|) &lt;=1
    int leftHeight = n.left != null ? n.left.height() : -1;
    int rightHeight = n.right != null ? n.right.height() : -1;
    return leftHeight - rightHeight &lt;= 1;
  }



Should return true if the tree is balanced, but, it takes a node in, computes the height of the left and right sides, and compares the differences.

This method is broken.... Just because the height of each side of the tree (left, and right) are similar, does not mean that each side is also balanced. Consider a tree like:

    //             0
    //            / \
    //           1   4
    //          /   /
    //         2   5
    //        /   /
    //       3   6


When you test the root, you will determine that both sides have the same height, yet, the tree is far from balanced.