Maximum Width of Binary Tree

medium

Given the root of a binary tree, return the maximum width of any level. The width of a level is the number of positions between its leftmost and rightmost non-null nodes inclusive, counting the null gaps between them as if the tree were a complete binary tree (a left child sits at index 2i, a right child at 2i + 1).

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Index nodes as in a complete binary tree: node i has children 2i and 2i+1.
A level's width is its last index minus its first index plus one — this counts the null gaps.
Normalize each level by subtracting its leftmost index so the indices don't overflow.

Common doubts

Width includes the null gaps between the outermost real nodes, which node counts ignore; the index span captures them.
Indices double each level (~2^depth) and overflow on deep trees; subtracting the level's first index keeps them small without changing any width.
Yes — record the leftmost index at each depth (via a left-first DFS) and maximize idx - first[depth] + 1.

Interview follow-ups

Track the depth alongside the maximum width when you update it.
It assigns each node the exact column it would occupy in a full tree, so index differences equal gap-inclusive distances.

Fun facts

  • The 2i / 2i+1 indexing is the same scheme used to store a binary heap in a flat array.
  • Normalizing per level is what lets languages with 64-bit ints handle trees thousands of levels deep.

Asked at

AmazonMicrosoftBloomberg
Frequently Sometimes Occasionally
Example 1
Input: root = [1, 3, 2, 5, 3, null, 9]
Output: 4
The widest level is the last, spanning indices 0..3 (nodes 5, 3, _, 9): width 4.
Example 2
Input: root = [1, 3, 2, 5]
Output: 2
Level 1 has both children, indices 0 and 1: width 2.
Constraints

- The number of nodes is in the range [1, 3000] - -100 <= Node.val <= 100

Solve this problem →