Problem 662 · LeetCode 662(opens in a new tab)
Maximum Width of Binary Tree
MediumBreadth-first search
You are given the root of a binary tree. Picture each level as if the tree were complete down to that level, with a slot for every possible node. The width of a level is the number of slots from its leftmost real node to its rightmost real node, counting the empty slots between them.
Return the largest width over all levels. The answer fits in a 32-bit signed integer.
Example 1
Input: root = [5, 1, 8, 6, null, null, 2] Output: 4 Why: the bottom level spans 6, gap, gap, 2
2 more examples and the constraints
Example 2
Input: root = [2, 4, 6, 8, null, null, 10, 12, null, null, 14] Output: 8 Why: 12 sits in slot 0 and 14 in slot 7 of the last level
Example 3
Input: root = [6] Output: 1 Why: a single node is a level of width 1
Constraints
- 1 ≤ number of nodes ≤ 3,000
- −100 ≤ Node.val ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DFS with leftmost per depthO(n)
- BFS with positionsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 3,000 nodes | Verdict |
|---|---|---|---|
| DFS with leftmost per depth | O(n) | Passes; recursion as deep as the tree | |
| BFS with positions | O(n) | Best; no deep recursion |
n = number of nodes, h = height, w = largest number of nodes on one level. Both visit each node once; BFS avoids a 3,000-deep call stack.
Edge cases to test
- One node. The answer is 1.
- A chain. Every level has one node, so the width is 1, however the chain bends.
- Very deep trees. Raw positions double each level and overflow any integer; subtract the level’s first position every time.
- Widest level in the middle. Take the maximum over all levels, not just the last one.
Common mistakes
- Counting only the real nodes on a level and ignoring the gaps between them.
- Letting positions grow unchecked, so they overflow on a deep tree.
- Measuring the width after the level’s children were added to the queue, which mixes two levels.
How to talk through it
- 1Clarify. Do gaps between nodes count? Do slots outside the leftmost and rightmost nodes count?
- 2Number the slots. Heap numbering, left 2p and right 2p + 1, turns gaps into arithmetic.
- 3Pick BFS. A level-by-level queue holds exactly one level, so its ends give the width.
- 4Guard overflow. Subtract the first position of each level before computing children.
- 5Test out loud. Try one node, a chain, and a tree with a gap in the middle.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?