Skip to problem
←

Maximum Width of Binary Tree

Medium 0 attempts

Given the root of a nonempty binary tree, return its maximum width across all levels.

At each level, imagine the node positions in a complete binary tree. Count positions from the leftmost real node to the rightmost real node, including both endpoints and any missing positions between them. Missing positions outside those endpoints do not count.

A level containing just one real node has width 1, even if that node is far to the left or right. In Example 1, the last level is [5,3,null,9], so its width is 4, not 3.

Function contract

Implement maximumWidthOfBinaryTree(root). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return the maximum number of complete-tree positions from the leftmost to rightmost real node on one level, inclusive. Count gaps between them.

Example 1

Input
root = [1,3,2,5,3,null,9]
Output
4

Example 2

Input
root = [1]
Output
1
Visual Aid
Width includes internal gaps
A level with nodes 5, 3, missing, and 9 has width four53missing94 positions, including the gap

The final level of Example 1 has three real nodes spanning four positions.

Constraints
  • 1 <= number of nodes <= 3000
  • -100 <= Node.val <= 100
  • The maximum width fits in a signed 32-bit integer.

Approach: BFS with Position Indexing

Assign a position index to each node: root is 0, left child is 2pos, right is 2pos+1. Width at each level is rightmost - leftmost + 1. Normalize positions by subtracting the first active position at each level before creating child positions. Read that first position at queue[head], since earlier queue entries have already been processed. BigInt keeps position arithmetic exact.

javascript
function maximumWidthOfBinaryTree(root) {
  if (!root) return 0;
  let maxWidth = 0;
  const queue = [[root, 0n]];
  let head = 0;
  while (head < queue.length) {
    const size = queue.length - head;
    const first = queue[head][1];
    let last = first;
    for (let i = 0; i < size; i++) {
      const [node, pos] = queue[head++];
      last = pos;
      const offset = pos - first;
      if (node.left) queue.push([node.left, 2n * offset]);
      if (node.right) queue.push([node.right, 2n * offset + 1n]);
    }
    maxWidth = Math.max(maxWidth, Number(last - first + 1n));
  }
  return maxWidth;
}

Time Complexity: O(n)

Space Complexity: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript