Home
DSA Patterns
Breadth-First Search
Maximum Width of Binary Tree
Maximum Width of Binary Tree (LeetCode 662)
Maximum Width of Binary Tree (LeetCode 662): find the widest level of the tree (including nulls between end nodes).
Examples
The last level spans slots 0 to 3, including one empty slot.
The last level spans slots 0 to 6: 6 and 7 with five empty slots between.
The second level, 3 and 2, is widest.
Problem Understanding
Find the maximum width of the binary tree under root, taken over all of its levels.
- Width: The number of nodes between the leftmost and rightmost non-null nodes in a level, including the null nodes between them.
- Imagine filling the tree into a complete binary tree structure. We count the distance from Start to End index.
Algorithm Strategy
Give every node the index it would have in a complete binary tree, and the gaps take care of themselves.
- Indices: the root is
0. A node at indexihas its left child at2iand its right child at2i + 1. Two nodes on a level with indices 0 and 3 have two empty slots between them. - BFS with pairs: the queue holds
(node, index). - Width at the start of a level: the front of the queue holds the smallest index,
first, and the back holds the largest,last. The width islast - first + 1. - Keep indices small: as each node is dequeued, subtract
firstfrom its index before computing its children's. Every level then starts near 0, however deep the tree is.
Interactive Visualization
i = INDEX ENQUEUED WITH · CHILDREN OF i ARE 2i AND 2i + 1
ENQUEUE (root, 0)
first
:
last
:
best
0
level slots
No level being measured
queue (front first)
best = 0. Put (1, index 0) in the queue
Next
A new level of 1 node: first = 0 at the front, last = 0 at the back
Tree
Every node shows the index it was enqueued with. When a level starts, its slots are laid out beside the tree from first to last (nodes and ∅ gaps alike) and the width is the number of slots. Try Example 2, where the last level has five empty slots between its two nodes.
Dry Run
Tree: [1, 3, 2, 5, 3, null, 9] (LeetCode example 1).
| Level | Queue at start (value, index) | first | last | width | best |
|---|---|---|---|---|---|
| 0 | (1, 0) | 0 | 0 | 1 | 1 |
| 1 | (3, 0), (2, 1) | 0 | 1 | 2 | 2 |
| 2 | (5, 0), (3, 1), (9, 3) | 0 | 3 | 4 | 4 |
Slot 2 on the last level is empty (it is where 2's left child would be) but it lies between the first and last nodes, so it counts. The method returns 4.
Edge Cases & Common Mistakes
Edge Cases:
- Single node: width 1.
- Index size: subtracting
firstkeeps indices below twice the widest level seen so far, and LeetCode guarantees the answer fits in a 32-bit integer, but twice that does not, so Java, C++ and C keep indices in 64-bit integers. Python integers and JavaScript numbers hold them exactly.
Common Mistakes:
- Counting only the non-null nodes on a level. The empty slots between the first and last node are part of the width.
- Measuring the width after the level has been dequeued, when the queue already holds the next level.
Solution Code
BFS with Indexing Normalization.
Maximum Width of Binary Tree Code
1var widthOfBinaryTree = function(root) {2 let best = 0;3 const queue = [[root, 0]];4 let head = 0;5 while (head < queue.length) {6 const size = queue.length - head;7 const first = queue[head][1];8 const last = queue[queue.length - 1][1];9 best = Math.max(best, last - first + 1);10 for (let i = 0; i < size; i++) {11 let [node, index] = queue[head++];12 index -= first;13 if (node.left) {14 queue.push([node.left, 2 * index]);15 }16 if (node.right) {17 queue.push([node.right, 2 * index + 1]);18 }19 }20 }21 return best;22};
Maximum Width of Binary Tree in Python, Java, C++, TypeScript and C
Maximum Width of Binary Tree in Python
from collections import deque
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
best = 0
queue = deque([(root, 0)])
while queue:
size = len(queue)
first = queue[0][1]
last = queue[-1][1]
best = max(best, last - first + 1)
for _ in range(size):
node, index = queue.popleft()
index -= first
if node.left:
queue.append((node.left, 2 * index))
if node.right:
queue.append((node.right, 2 * index + 1))
return bestMaximum Width of Binary Tree in Java
class Solution {
private static class Entry {
final TreeNode node;
final long index;
Entry(TreeNode node, long index) {
this.node = node;
this.index = index;
}
}
public int widthOfBinaryTree(TreeNode root) {
long best = 0;
Deque<Entry> queue = new ArrayDeque<>();
queue.offer(new Entry(root, 0));
while (!queue.isEmpty()) {
int size = queue.size();
long first = queue.peekFirst().index;
long last = queue.peekLast().index;
best = Math.max(best, last - first + 1);
for (int i = 0; i < size; i++) {
Entry entry = queue.poll();
long index = entry.index - first;
if (entry.node.left != null) {
queue.offer(new Entry(entry.node.left, 2 * index));
}
if (entry.node.right != null) {
queue.offer(new Entry(entry.node.right, 2 * index + 1));
}
}
}
return (int) best;
}
}Maximum Width of Binary Tree in C++
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
unsigned long long best = 0;
deque<pair<TreeNode*, unsigned long long>> q;
q.push_back({root, 0});
while (!q.empty()) {
int size = q.size();
unsigned long long first = q.front().second;
unsigned long long last = q.back().second;
best = max(best, last - first + 1);
for (int i = 0; i < size; i++) {
auto [node, index] = q.front();
q.pop_front();
index -= first;
if (node->left) {
q.push_back({node->left, 2 * index});
}
if (node->right) {
q.push_back({node->right, 2 * index + 1});
}
}
}
return (int)best;
}
};Maximum Width of Binary Tree in TypeScript
function widthOfBinaryTree(root: TreeNode | null): number {
let best = 0;
const queue: [TreeNode, number][] = [[root!, 0]];
let head = 0;
while (head < queue.length) {
const size = queue.length - head;
const first = queue[head][1];
const last = queue[queue.length - 1][1];
best = Math.max(best, last - first + 1);
for (let i = 0; i < size; i++) {
let [node, index] = queue[head++];
index -= first;
if (node.left) {
queue.push([node.left, 2 * index]);
}
if (node.right) {
queue.push([node.right, 2 * index + 1]);
}
}
}
return best;
}Maximum Width of Binary Tree in C
struct Entry {
struct TreeNode* node;
unsigned long long index;
};
int widthOfBinaryTree(struct TreeNode* root) {
unsigned long long best = 0;
struct Entry* queue = malloc(3000 * sizeof(struct Entry));
int head = 0, tail = 0;
queue[tail++] = (struct Entry){root, 0};
while (head < tail) {
int size = tail - head;
unsigned long long first = queue[head].index;
unsigned long long last = queue[tail - 1].index;
if (last - first + 1 > best) {
best = last - first + 1;
}
for (int i = 0; i < size; i++) {
struct Entry entry = queue[head++];
unsigned long long index = entry.index - first;
if (entry.node->left) {
queue[tail++] = (struct Entry){entry.node->left, 2 * index};
}
if (entry.node->right) {
queue[tail++] = (struct Entry){entry.node->right, 2 * index + 1};
}
}
}
free(queue);
return (int)best;
}More practice: DSA interview questions with answers · patterns cheat sheet
