Maximum Width

35 min · widthOfBinaryTree()

Two employees can sit at opposite ends of an org-chart row even when several empty positions lie between them. Those gaps still make the row wide.

Given the root of a binary tree, return the largest width among all depths. A level's width is the distance from its leftmost present node to its rightmost present node, including the missing positions between them.

Use complete-tree positions to measure that distance: place the root at position 1; a node at position i would place its left child at 2 * i and its right child at 2 * i + 1. For each level, compute rightmost - leftmost + 1.

Ground rules:

  • Missing positions inside the two extremes count toward the width.
  • Missing positions outside those extremes don't count.
  • Return 0 for an empty tree.

Constraints

  • 0 <= node count <= 3_000
  • The root is at depth 0, and no node has depth greater than 30.
  • -1_000 <= node.val <= 1_000
  • Every level width fits in a signed 32-bit integer.

Hints

Carry more than the node

Queue each node together with the position it would occupy in a complete tree. The first and last positions in one level determine that level's width.

Freeze one level

Save the queue length before processing. Read exactly that many node-position pairs, then compare the level's span with the best span seen so far.

Keep positions small

Before creating child positions, subtract the first position in the current level from every position. A shared shift doesn't change the width.

Follow-up

If the depth cap disappeared, why would normalizing positions at every level protect languages with fixed-width integers?

Visible cases

Examples

Example 1

ready
Input
root = [
  1,
  3,
  2,
  5,
  3,
  null,
  9
]
Expected
4
Why
the third level spans four complete-tree positions

Example 2

ready
Input
root = [
  1,
  3,
  2,
  5,
  null,
  null,
  9,
  6,
  null,
  null,
  7
]
Expected
8
Why
the deepest nodes sit eight positions apart when the gaps count

Example 3

ready
Input
root = [
  1
]
Expected
1
Why
one node occupies one position

Interview signal

Asked at

AmazonGoogleBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite