Naive O(N²)

boolean isBalanced(Node n) {
  if (n == null) return true;
  if (Math.abs(height(n.left) - height(n.right)) > 1) return false;
  return isBalanced(n.left) && isBalanced(n.right);
}
Advertisement

O(N) with early return

int check(Node n) {
  if (n == null) return 0;
  int left = check(n.left);
  if (left == -1) return -1;
  int right = check(n.right);
  if (right == -1) return -1;
  if (Math.abs(left - right) > 1) return -1;
  return 1 + Math.max(left, right);
}
boolean isBalanced(Node root) { return check(root) != -1; }
Advertisement

The insight

Compute height + check balance in one pass. Return -1 as failure signal — propagates up.

Complexity

O(N) time, O(H) space.