You are given the root of a binary tree. Call the tree balanced if, at every single node, the heights of its left and right subtrees differ by no more than 1. An empty subtree has height 0.
Return true if the tree is balanced and false if it is not. An empty tree counts as balanced.
Example 1
Input: root = [4, 2, 7, 1] Output: true Why: at every node the two sides differ by at most 1
2 more examples and the constraints
Example 2
Input: root = [1, 2, 2, 3, null, null, 3, 4, null, null, 4] Output: false Why: the root is even, but each 2 has a side 2 deeper
Example 3
Input: root = [] Output: true Why: an empty tree is balanced
Constraints
- 0 ≤ number of nodes ≤ 5,000
- −10,000 ≤ node value ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check each node from the topO(n log n)
- One pass from the bottomO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a balanced tree of 5,000 nodes | Verdict |
|---|---|---|---|
| Check each node from the top | O(n log n) | Passes; repeats work | |
| One pass from the bottom | O(n) | Best; each node once |
n = number of nodes, h = height of the tree.
Edge cases to test
- Empty tree.
rootis null: return true. - Balanced root, unbalanced child. Example 2: the root's sides are equal, but a node lower down is lopsided. Checking only the root is wrong.
- A chain. [1, null, 2, null, 3] is false: the root has a right side of height 2 and a left side of 0.
- One missing child. [1, 2] is true: heights 1 and 0 differ by exactly 1.
Common mistakes
- Comparing only the root's two heights and forgetting every other node.
- Measuring balance by the number of nodes on each side instead of the height.
- Using −1 as the failure signal but forgetting to pass it up when a child returns it.
How to talk through it
- 1Clarify. Does the rule apply at every node or only the root? Is an empty tree balanced?
- 2Give the direct version. Check heights at the root, then recurse; note that heights are measured again and again.
- 3Combine the two questions. One post-order walk can return the height and signal failure with −1.
- 4Code the helper. Left first, bail out on −1, then right, then compare and return height plus 1.
- 5Test out loud. Run the empty tree, a chain, and a tree whose root looks fine but a child does not.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?