Maximum Width of Binary Tree (LeetCode 662): Solution and Explanation
The width of a level in a binary tree is the distance from its leftmost node to its rightmost node, counting the empty slots in between as if the tree were complete. Return the largest width over all levels.
Watch it run step by step
Try your own input and write the code →Intuition
Counting the nodes on each level is not enough, because the gaps between nodes count toward the width. A level with only two nodes, one at the far left and one at the far right, can be very wide. One brute force idea is to insert null placeholders for missing children during a level order traversal and measure each level including placeholders, but the number of placeholders doubles every level, so a skinny tree of depth 3,000 would explode.
The better idea is to give each node a coordinate instead of storing the gaps. Number positions the way a binary heap does: the root is 0, and a node at position p has its left child at 2p and its right child at 2p + 1. Under this scheme, a node's position is exactly where it would sit in a complete tree, so the width of a level is just the rightmost position minus the leftmost position plus one. No placeholders are needed.
A breadth-first search fits naturally because it handles one level at a time, and within a level the queue holds nodes from left to right. The remaining problem is size. Positions double with each level, so in a deep, lopsided tree they grow like 2 to the power of the depth and overflow 64-bit integers in Java or C++. Since only differences within a level matter, you can subtract the level's leftmost position from every position on that level before computing children. That keeps the numbers small without changing any width.
Approach: BFS with normalized heap positions
- If the tree is empty, return 0. Otherwise start a queue holding
(root, 0)and setmax_width = 0. - For each level, record
size = len(queue)and read the leftmost positionleftfrom the front of the queue. - Pop each of the
sizenodes, normalize its position withpos -= left, and updaterightto its original position. - Push the left child with position
2 * posand the right child with position2 * pos + 1, using the normalizedpos. - After the level, update
max_widthwithright - left + 1. - When the queue is empty, return
max_width.
Step-by-step example
root = [1, 3, 2, 5, 3, null, 9]
- Level 0 holds only the root at position 0, so the width is 1. Its children enter as 3 at position 0 and 2 at position 1.
- Level 1 has
left = 0. Node 3 at position 0 pushes 5 at 0 and 3 at 1. Node 2 at position 1 has no left child and pushes 9 at position 3. - The rightmost position on level 1 is 1, so its width is 1 - 0 + 1 = 2, and
max_widthbecomes 2. - Level 2 holds positions 0, 1 and 3, with
left = 0andright = 3, so the width is 3 - 0 + 1 = 4. - No more nodes are queued, so the function returns 4. The gap at position 2 counts toward the width even though no node lives there.
Code: Python, Java, C++
1class Solution:
2 def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
3 if not root:
4 return 0
5
6 max_width = 0
7 queue = deque([(root, 0)]) # (node, position)
8
9 while queue:
10 size = len(queue)
11 _, left = queue[0]
12 right = left
13
14 for _ in range(size):
15 node, pos = queue.popleft()
16 pos -= left # Normalize to prevent overflow
17 right = pos + left
18
19 if node.left:
20 queue.append((node.left, 2 * pos))
21 if node.right:
22 queue.append((node.right, 2 * pos + 1))
23
24 max_width = max(max_width, right - left + 1)
25
26 return max_width1class Solution {
2 public int widthOfBinaryTree(TreeNode root) {
3 if (root == null) return 0;
4
5 int maxWidth = 0;
6 Queue<TreeNode> nodes = new LinkedList<>();
7 Queue<Integer> positions = new LinkedList<>();
8 nodes.offer(root);
9 positions.offer(0);
10
11 while (!nodes.isEmpty()) {
12 int size = nodes.size();
13 int left = positions.peek();
14 int right = left;
15
16 for (int i = 0; i < size; i++) {
17 TreeNode node = nodes.poll();
18 int pos = positions.poll() - left; // Normalize to prevent overflow
19
20 right = pos + left;
21
22 if (node.left != null) {
23 nodes.offer(node.left);
24 positions.offer(2 * pos);
25 }
26 if (node.right != null) {
27 nodes.offer(node.right);
28 positions.offer(2 * pos + 1);
29 }
30 }
31
32 maxWidth = Math.max(maxWidth, right - left + 1);
33 }
34
35 return maxWidth;
36 }
37}1class Solution {
2public:
3 int widthOfBinaryTree(TreeNode* root) {
4 if (!root) return 0;
5
6 int maxWidth = 0;
7 queue<pair<TreeNode*, unsigned long long>> q;
8 q.push({root, 0});
9
10 while (!q.empty()) {
11 int size = q.size();
12 unsigned long long left = q.front().second;
13 unsigned long long right = left;
14
15 for (int i = 0; i < size; i++) {
16 auto [node, pos] = q.front();
17 q.pop();
18 pos -= left; // Normalize
19
20 right = pos + left;
21
22 if (node->left) {
23 q.push({node->left, 2 * pos});
24 }
25 if (node->right) {
26 q.push({node->right, 2 * pos + 1});
27 }
28 }
29
30 maxWidth = max(maxWidth, (int)(right - left + 1));
31 }
32
33 return maxWidth;
34 }
35};Time and space complexity
O(n)
Every node is enqueued and dequeued exactly once, with constant work for normalization and pushing children.
O(n)
The queue holds at most one full level of nodes, which can be about n / 2 for a complete tree.
Other approaches
DFS with leftmost position per depth (time O(n), space O(h))
Run a preorder DFS that carries each node's depth and position. The first node seen at each depth is the leftmost, so store its position in a list; every node then computes pos - leftmost[depth] + 1 as a candidate width. It uses O(h) recursion space and avoids a queue, but needs the same care with large positions.
Common mistakes
- Counting only non-null nodes per level. Width includes the gaps between the outermost nodes, so a node count underestimates it.
- Skipping normalization in Java or C++. Positions double each level, and a chain of 3,000 nodes overflows even a 64-bit integer.
- Computing children from the unnormalized position after normalizing on some levels and not others. All positions on a level must use the same offset.
- Measuring width as
right - leftwithout adding one. A level with a single node has width 1, not 0.
Frequently asked questions
Why number nodes 2 × pos and 2 × pos + 1?
That is how a complete binary tree is laid out in an array, so each node's number is its column in a full tree. The distance between two numbers on the same level then includes every missing node between them.
Why subtract the leftmost position on each level?
Positions grow exponentially with depth and overflow fixed-width integers. Width only depends on differences within a level, so shifting every position on a level by the same amount keeps values small without changing the answer.
BFS or DFS for maximum width of a binary tree?
Both run in O(n). BFS reads naturally because width is defined per level, while DFS uses only O(h) stack space and tracks the first position seen at each depth.