Given the root of a binary tree, return the maximum width of any level. The width of a level is the number of positions between its leftmost and rightmost non-null nodes inclusive, counting the null gaps between them as if the tree were a complete binary tree (a left child sits at index 2i, a right child at 2i + 1).
The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [1, 3, 2, 5, 3, null, 9] Output: 4 The widest level is the last, spanning indices 0..3 (nodes 5, 3, _, 9): width 4.
Input: root = [1, 3, 2, 5] Output: 2 Level 1 has both children, indices 0 and 1: width 2.
- The number of nodes is in the range [1, 3000] - -100 <= Node.val <= 100
The width counts the null gaps between the outermost real nodes on a level, so plain node counts won't do. Assign each node the array index it would have in a complete binary tree: root 0, and a node at index i has children 2i and 2i+1. A level's width is then rightmostIndex − leftmostIndex + 1. To keep indices from exploding on deep trees, normalize each level by subtracting its leftmost index.
“Do null gaps count?”
Yes — width spans from the leftmost to the rightmost real node, including the missing positions between them.
“Could indices overflow?”
On deep trees yes; normalize per level (subtract the leftmost index) to keep them small.
I index nodes as in a complete tree: a node at i has children 2i and 2i+1.
Each level's width is its last index minus its first index plus one; I normalize per level so the indices don't overflow.
Worked example — tree [1, 3, 2, 5, 3, null, 9]
1(0)
/ \
3(0) 2(1)
/ \ \
5(0)3(1) 9(3)
level 2 indices: 0, 1, 3 -> width 3 - 0 + 1 = 4
answer: 4
Children at 2i and 2i+1 encode each node's horizontal position including the empty slots.
The outermost indices on a level, differenced, count the gap-inclusive span.
Subtracting each level's leftmost index resets it toward 0, keeping numbers bounded without changing widths.
| DFS with per-depth first index | BFS with indices | |
|---|---|---|
| Idea | Record leftmost index per depth; max(idx - first) | Per level, last index - first index + 1 |
| Time | O(n) | O(n) |
| Space | O(height) | O(n) |
Both index like a complete tree and normalize; BFS reads the width most directly. Full code is in the Approaches selector below.
Key takeaway
Index nodes as in a complete tree (children 2i, 2i+1); a level's width is last index − first index + 1. Normalize per level to avoid overflow. O(n) time.
bfs with (node, idx):
width = last idx - first idx + 1 on each level
children get 2*(idx-first) and 2*(idx-first)+1