Maximum Width of Binary Tree
Pattern: Level order BFS
Number nodes as in a full tree: the root is 0 and the children of p are 2p and 2p + 1. A level's width is its last position minus its first plus 1, gaps included. Subtract the first position at every level so the numbers stay small.
The problem
Return the largest width of any level, where the width counts every position between the leftmost and rightmost nodes of
the level, including missing ones. [1, 3, 2, 5, 3, null, 9] gives 4. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Why can you not just count the nodes in a level?
- How can each node get a position as if the tree were full?
- Why might the positions overflow?
Hints
Brute force, and why it fails
Fill a full-tree array with nulls and scan each level: exponential space on a deep tree.
The key insight
Positions give the width directly, and subtracting each level's first position keeps them bounded without changing any difference.
Dry run
| width | 1 |
|---|
[1, 3, 2, 5, 3, null, 9]. Level 0: 1 at position 0. Width 1.
The plan
queue = [root]
while queue:
size = len(queue); level = []
repeat size times: n = pop front; level += n; push n's children
width = last position - first position + 1
Complexity
- Time
O(n)- Space
O(w)
One BFS pass with a position per node.
Edge cases
- One node: 1.
- A long chain: the shift keeps positions at 0 or 1.
- Wide gaps on the last level.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int widthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
Queue<Object[]> q = new ArrayDeque<>(); // {node, position as in a full tree}
q.add(new Object[]{root, 0L});
long best = 0;
while (!q.isEmpty()) {
int size = q.size();
long first = (Long) q.peek()[1]; // positions in each level are shifted so the first is 0
long last = first;
for (int i = 0; i < size; i++) {
Object[] item = q.poll();
TreeNode node = (TreeNode) item[0];
long p = (Long) item[1] - first;
last = p;
if (node.left != null) q.add(new Object[]{node.left, 2 * p});
if (node.right != null) q.add(new Object[]{node.right, 2 * p + 1});
}
best = Math.max(best, last + 1);
}
return (int) best;
}
}C++
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if (root == NULL) return 0;
queue<pair<TreeNode*, unsigned long long>> q; // {node, position as in a full tree}
q.push(make_pair(root, 0ULL));
unsigned long long best = 0;
while (!q.empty()) {
int size = static_cast<int>(q.size());
unsigned long long first = q.front().second, last = 0; // shift each level so the first is 0
for (int i = 0; i < size; i++) {
pair<TreeNode*, unsigned long long> item = q.front();
q.pop();
unsigned long long p = item.second - first;
last = p;
if (item.first->left != NULL) q.push(make_pair(item.first->left, 2 * p));
if (item.first->right != NULL) q.push(make_pair(item.first->right, 2 * p + 1));
}
best = max(best, last + 1);
}
return static_cast<int>(best);
}
};Python
from collections import deque
class Solution:
def widthOfBinaryTree(self, root) -> int:
if not root:
return 0
q, best = deque([(root, 0)]), 0 # (node, position as in a full tree)
while q:
first = q[0][1]
for _ in range(len(q)):
node, p = q.popleft()
p -= first # shift each level so the first is 0
if node.left:
q.append((node.left, 2 * p))
if node.right:
q.append((node.right, 2 * p + 1))
best = max(best, p + 1)
return bestCommon mistakes
- Counting nodes instead of positions.
- Not shifting positions, which overflows on deep trees.