Maximum Width of Binary Tree
Medium
Topics
Given the root of a binary tree, return the maximum width. The width of a level is the number of positions between its leftmost and rightmost non-null nodes (as if the level were a full binary tree), counting the null slots between them.
Example 1
null marks a missing child.Input: root = [1,3,2,5,3,null,9] Output: 4
Example 2
Input: root = [1,3,2,5,null,null,9,6,null,7] Output: 7
Constraints
- 1 <= number of nodes <= 3000
- -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Width counts the null slots between the outermost real nodes, so counting nodes per level is not enough — you need their positions. Give the root index 0 and a node at index i children at 2i and 2i + 1, the standard heap numbering. The width of a level is then last - first + 1.
Done naively the index doubles every level and overflows fast. A right-leaning path of 32 nodes already needs a 31-bit index, 64 nodes needs 63 bits, and at the stated limit of 3,000 nodes the index needs 2,999 bits — past int, past long, past anything but a big integer. Subtracting the level's first index before descending fixes this: on a full tree of 3,000 nodes the largest normalised index is 1,023.
Approach
- Hold the current level as pairs of node and index, starting with the root at 0.
- Take
firstas the index of the leftmost node; the level's width is the last index minusfirst, plus one. - Build the next level using the normalised position
p = idx - first, giving children2pand2p + 1. - Keep the largest width seen.
Dry Run
1
/ \
3 2
/ \ \
5 3 9
level nodes with index first last width
0 1@0 0 0 1
1 3@0 2@1 0 1 2
2 5@0 3@1 9@3 0 3 4 <- index 2 is the empty slot
answer 4Complexity
- Time — O(n): every node is enqueued and dequeued once.
- Space — O(w): where
wis the widest level. In the worst case that is O(n), for a complete tree whose bottom level holds half the nodes.
Common Pitfalls
- Skipping the per-level normalisation. Measured above: 32 nodes in a right-leaning path need 31 bits and 64 need 63, so both
intandlongoverflow well inside the constraints. This is the one thing an interviewer will probe on this problem. - Counting non-null nodes per level. The gaps between the extremes are part of the width, which is why level 2 above has width 4 and not 3.
- Padding each level with explicit nulls to make the arithmetic easy. That is O(2ⁱ) memory at depth
iand dies on a skewed tree. - A depth-first version that records the minimum and maximum index per depth works, but needs exactly the same normalisation — the overflow follows the indexing scheme, not the traversal order.
- Returning 0 for a single node. One node is width 1.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def widthOfBinaryTree(self, root):
if not root: return 0
best = 0; q = [(root, 0)]
while q:
first = q[0][1]; best = max(best, q[-1][1] - first + 1); nq = []
for node, idx in q:
p = idx - first
if node.left: nq.append((node.left, p * 2))
if node.right: nq.append((node.right, p * 2 + 1))
q = nq
return bestimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int widthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
int best = 0;
List<TreeNode> q = new ArrayList<>();
List<Long> idx = new ArrayList<>();
q.add(root);
idx.add(0L);
while (!q.isEmpty()) {
long first = idx.get(0);
best = Math.max(best, (int)(idx.get(idx.size() - 1) - first + 1));
List<TreeNode> nq = new ArrayList<>();
List<Long> ni = new ArrayList<>();
for (int i = 0; i < q.size(); i++) {
long p = idx.get(i) - first;
TreeNode node = q.get(i);
if (node.left != null) {
nq.add(node.left);
ni.add(p * 2);
}
if (node.right != null) {
nq.add(node.right);
ni.add(p * 2 + 1);
}
}
q = nq;
idx = ni;
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int widthOfBinaryTree(TreeNode* root) {
if (!root) return 0;
int best = 0;
vector<pair<TreeNode*,long long>> q = { {
root, 0
}
};
while (!q.empty()) {
long long first = q[0].second;
best = max(best, (int)(q.back().second - first + 1));
vector<pair<TreeNode*,long long>> nq;
for (auto& pr : q) {
long long p = pr.second - first;
if (pr.first->left) nq.push_back({pr.first->left, p * 2});
if (pr.first->right) nq.push_back({pr.first->right, p * 2 + 1});
}
q = nq;
}
return best;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var widthOfBinaryTree = function(root) {
if (!root) return 0;
let best = 0, q = [[root, 0]];
while (q.length) {
const first = q[0][1];
best = Math.max(best, q[q.length - 1][1] - first + 1);
const nq = [];
for (const [node, idx] of q) {
const p = idx - first;
if (node.left) nq.push([node.left, p * 2]);
if (node.right) nq.push([node.right, p * 2 + 1]);
}
q = nq;
}
return best;
};