Checking if a binary tree is balanced class BinaryTreeNode {

  private BinaryTreeNode left;
  private BinaryTreeNode right;
  private int data;

  BinaryTreeNode(int d) {
    data = d;
  }

  public void insertLeft(BinaryTreeNode n) {
    this.left = n;
  }

  public void insertRight(BinaryTreeNode n) {
    this.right = n;
  }

  public int height() {
    // height = Max(Hl, Hr) + 1
    int leftHeight = this.left != null ? left.height() : -1;
    int rightHeight = this.right != null ? right.height() : -1;
    return Math.max(leftHeight, rightHeight) + 1;
  }

  public String toString() {
    String leftStr = this.left == null ? "" : this.left.toString();
    String rightStr = this.right == null ? "" : this.right.toString();
    return leftStr + " : " + data + " : " + rightStr;
  }

  public static void main(String[] s) {
    BinaryTreeNode n  = new BinaryTreeNode(0);//             0         l0
                                              //            / \
    BinaryTreeNode l1 = new BinaryTreeNode(1);//           1   4       l1
                                              //          /
    BinaryTreeNode l2 = new BinaryTreeNode(2);//         2             l2
                                              //        /
    BinaryTreeNode l3 = new BinaryTreeNode(3);//       3               l3
    l2.insertLeft(l3);
    l1.insertLeft(l2);
    n.insertLeft(l1);
    n.insertRight(new BinaryTreeNode(4));
    System.out.println(n.height());
    System.out.println(isBalanced(n));
  }

  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;
  }
}
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.