Trees · Easy
Balanced Binary Tree: the idea to remember.
Check whether every node has child subtree heights differing by at most one.
The core insight
Return a height or a negative sentinel when any subtree is unbalanced.
Why it works
Each return certifies the entire subtree, not just its root. A negative result propagates immediately.
The mistake to avoid
Checking the root alone misses an unbalanced descendant. Recomputing heights at every node can take O(n²).
Time: O(n)Space: O(h) call stack
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
boolean isBalanced(TreeNode root) { return balancedHeight(root) != -1; }
int balancedHeight(TreeNode node) {
if (node == null) return 0;
int l = balancedHeight(node.left);
if (l == -1) return -1;
int r = balancedHeight(node.right);
if (r == -1 || Math.abs(l - r) > 1) return -1;
return 1 + Math.max(l, r);
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.