Balanced Binary Tree
Master this topic with zero to advance depth.
Balanced Binary Tree
Check if a tree is height-balanced.
Examples
Level I: Recursive DFS (Top-Down)
Intuition
For each node, compute the height of its left and right subtrees. If the difference is , it's not balanced. Then recurse for both children.
Detailed Dry Run
root(3): H(L)=1, H(R)=2. Diff=1. OK. Recurse(9) and Recurse(20).
Level II: Recursive with Memoization
Intuition
To optimize the approach, we can cache the height of each node in a HashMap. This ensures that we only calculate the height of each node once, bringing the complexity down to .
Logic
- Use a Map to store
node -> height. - In
height(node), return map value if present. - Recurse for balanced property using cached heights.
Detailed Dry Run
Map: {9:1, 15:1, 7:1, 20:2, 3:3}. Heights are fetched from Map in O(1) during balance check.
Level III: Optimal (Bottom-Up DFS)
Intuition
Compute heights bottom-up. If any subtree is unbalanced, return -1 to signal failure to parents immediately.
Detailed Dry Run
Node(20): L=1, R=1 -> height=2. root(3): L=1, R=2 -> height=3. Balanced.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.