Balanced Binary Tree – Solution & Complexity
Solution Walkthrough
Step 1: Understand the balance condition
- Balance is a local rule that must hold at every node, not just at the root.
- That means we need subtree heights, but we also need to know whether a deeper subtree has already failed.
Step 2: Brute-force by recomputing heights
- For each node, compute the height of the left subtree and the right subtree, compare them, then recurse into both children.
- This is correct, but repeated height work can make it
O(n^2)on skewed trees.
Step 3: Return a sentinel when a subtree is already unbalanced
- A postorder traversal naturally computes child heights before the parent.
- If either child is already unbalanced, bubble up a sentinel like
-1immediately instead of continuing normal height math.
Step 4: Combine height and balance in one DFS
- Return the subtree height when everything below the node is balanced.
- Return
-1as soon as a node fails the balance check. - The tree is balanced exactly when the root does not return
-1.
Step 5: Dry run / postorder trace
Trace
root = [1,2,2,3,3,null,null,4,4].node left height right height return value leaf 40 0 1 leaf 40 0 1 node 3(left subtree)1 1 2 node 3(right child of left subtree)0 0 1 node 2(left child of root)2 1 3 node 2(right child of root)0 0 1 root 13 1 -1(unbalanced)Step 6: Common mistakes and follow-ups
- Computing height separately at every node, which degrades to
O(n^2). - Treating an empty tree as unbalanced when it should return
true. - Forgetting that a subtree already marked unbalanced should short-circuit immediately.
- Follow-up: how would you implement the same idea iteratively with an explicit postorder stack?
- Computing height separately at every node, which degrades to
Step 7: Edge cases to test mentally
[]and[1]are both balanced.- A chain of three nodes is unbalanced at the root.
- Perfect trees are balanced at every level.
- A tree can look balanced at the root but still fail deeper down, so every subtree must be checked.
Step 8: Final full solution and complexity
A single postorder DFS returns each subtree height once and uses
-1as an imbalance sentinel. Time isO(n), and extra stack space isO(h)wherehis the tree height.