Maximum Width of Binary Tree
Measure the widest level of a tree, gaps included, by numbering nodes as in a complete tree during BFS.
The problem
You get the root of a binary tree. Number the positions on each level as they would be in a complete binary tree; the width of a level is the number of positions from its leftmost node to its rightmost node, inclusive, counting the empty positions in between. Return the largest width of any level; you can assume it fits in a 32-bit signed integer.
Input root = [5, 1, 4, null, 6, null, 2]
Output 3
On the last level, 6 sits at position 1 and 2 at position 3 (counting from 0), so the width is 3 - 1 + 1 = 3.
Input root = [2, 7, 3, null, null, 8, 1, 6, null, null, 9]
Output 4
On the deepest level, 6 is at position 4 and 9 at position 7, so the width is 4, with two empty positions between them.
Key constraint: The tree can be 3,000 levels deep and positions double on every level, so they overflow any integer type unless you renumber each level to start at 0.
How to spot the pattern
- The width depends on positions, including empty ones, so each node needs the index it would have in a complete tree.
- You compare the leftmost and rightmost node of each level, which a level-by-level BFS hands you directly.
The idea
Give every node the index it would have in a complete binary tree: a node at position p has its children at 2p and 2p + 1. During BFS, the first and last nodes of a level then give its width as last - first + 1. To keep the numbers small, subtract the level's first position from every position on that level before computing the children; widths only depend on differences, so they don't change.
Brute force: Number positions without renumbering each level, which on a 3,000-level tree creates numbers thousands of bits long and overflows fixed-size integers.
Step by step
- 1Put
(root, 0)in a queue and setbest = 0. - 2For each level, note
first, the position of the first node in the queue, andsize, the number of nodes in it. - 3Pop each node with its position
p, setp = p - first, and push its children at2pand2p + 1. - 4After the level, the last node's renumbered position plus 1 is the level's width, so update
bestwith it. - 5Return
best.
See the pattern move
The tree bfs pattern on a small example. Step through it, or press play.
Code
from collections import deque
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
best = 0
queue = deque([(root, 0)]) # (node, position as if the tree were complete)
while queue:
size = len(queue)
first = queue[0][1] # position of the level's leftmost node
for _ in range(size):
node, pos = queue.popleft()
pos -= first # renumber so the level starts at 0 and numbers stay small
if node.left:
queue.append((node.left, 2 * pos))
if node.right:
queue.append((node.right, 2 * pos + 1))
best = max(best, pos + 1) # pos is now the last node's renumbered position
return bestComplexity
Time
O(n)
Space
O(w)
Each node is pushed and popped once, and w is the largest number of nodes on one level; renumbering keeps every position below twice the widest level, so 64-bit integers are enough.
Watch out for
- Using the raw positions without subtracting each level's first one: they double on every level and overflow on deep trees.
- Counting only the nodes that exist on a level: the width also counts the empty positions between the two end nodes.
- Computing
2 * p + 1in a 32-bit int in Java or C++: even after renumbering, a position can need 32 bits, so uselongorlong long.
Follow-up questions
Can you solve it with DFS?
Yes: pass each node's position and depth down, and remember the first position seen at each depth (a DFS that goes left first reaches each depth's leftmost node first). The width at a node is position - first[depth] + 1.
What if the width should count only the nodes that exist?
Then it is just the largest level size, which you get from size in the usual level order loop, with no positions at all.
In Hinglish
Har node ko complete tree wala index do: bacche 2p aur 2p + 1. Har level par pehle node ka index ghata do taaki number chhote rahein, aur width = last - first + 1.