Breadth-First Search
Medium

Maximum Width of Binary Tree

Find the widest level of the tree (including nulls between end nodes).
Problem Understanding

Given the root of a binary tree, return the maximum width of the given tree.

  • Width: The number of nodes between the leftmost and rightmost non-null nodes in a level, including the null nodes between them.
  • Imagine filling the tree into a complete binary tree structure. We count the distance from Start to End index.
Algorithm Strategy

Since we need to count nulls between nodes without actually storing null objects (which would waste memory), we use Indexing Strategy (Heap Indexing).

  1. Assign Indices:
    • Root is index 1 (or 0).
    • If node is i, Left Child is 2*i.
    • Right Child is 2*i + 1.
  2. BFS: Traverse level by level. Store (Node, Index) pairs in the Queue.
  3. Compute Width: For each level, Width = (Last_Index - First_Index) + 1.
Interactive Visualization
Step 1 / 1
Empty Heap

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep