Maximum Width of Binary Tree

Medium

Topics
TreeBFS

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

533129
the two ends of the widest level
Width spans the two shaded nodes and counts the missing nodes between them, so it is not the number of nodes on the level. Giving each node the position it would have in a complete tree turns the width into a subtraction: 4.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,3,2,5,3,null,9]
Output: 4

Example 2

6531279
the two ends of the widest level
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

  1. Hold the current level as pairs of node and index, starting with the root at 0.
  2. Take first as the index of the leftmost node; the level's width is the last index minus first, plus one.
  3. Build the next level using the normalised position p = idx - first, giving children 2p and 2p + 1.
  4. 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 4

Complexity

  • Time — O(n): every node is enqueued and dequeued once.
  • Space — O(w): where w is 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 int and long overflow 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 i and 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 best
Asked at ByteDance
SensAI
Beta
Tap the mic to stop voice mode