AlgoInsight

DSA problem

Maximum Width of Binary Tree

MediumTree Traversal - Level OrderPattern: Tree Traversal - Level Ordertop300AmazonMicrosoftBloombergGoogleApple

Given the root of a binary tree, return the maximum width of the tree. The width of one level is defined as the length of the range between the leftmost and the rightmost non-null nodes at that level, where missing nodes between them count toward the width (as if the tree were padded into a complete binary tree). The maximum width is the maximum value of this measure across all levels.

The clean way to express the index of each node is the heap-style indexing: if a node has index i, its left child has index 2 * i and its right child has index 2 * i + 1. With this scheme, the width of a level is simply rightmostIndex - leftmostIndex + 1, and we maintain it as we BFS the tree.

The dangerous trap is index overflow. For a left-skewed tree of depth 60 the indices double at every level and quickly blow past 2^63. To keep indices small, we re-anchor at every level: when we start processing a level, we subtract the index of its leftmost node from every node before computing child indices. That guarantees the leftmost index of every level is 0, keeping numbers in a safe range for any reasonable input. In Python and JavaScript we can also use BigInt/arbitrary precision, but the re-anchoring trick is the universally portable fix.

The algorithm visits every node once, so it runs in O(n) time and O(w) extra space for the queue, where w is the maximum width of the tree.

Examples

Example 1
Input: root = [1,3,2,5,3,null,9]
Output: 4
Explanation: Level 2 contains [5, 3, null, 9] when padded as a complete tree. The leftmost is 5 (col 0) and the rightmost is 9 (col 3), so the width is 3 - 0 + 1 = 4.
Example 2
Input: root = [1,3,2,5,null,null,9,6,null,7]
Output: 7
Explanation: On the deepest level the leftmost node is 6 and the rightmost is 7, padded with nulls in between, giving a width of 7.
Example 3
Input: root = [1,3,2,5]
Output: 2
Explanation: Level 1 has two nodes [3, 2] adjacent, width 2; deeper levels are narrower.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-treebfslevel-orderqueue

Browse all DSA problems