Breadth-First Search
Medium
Maximum Width of Binary Tree
Find the widest level of the tree (including nulls between end nodes).
15 min
Solve on LeetCodeProblem 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).
- Assign Indices:
- Root is index
1(or0). - If node is
i, Left Child is2*i. - Right Child is
2*i + 1.
- Root is index
- BFS: Traverse level by level. Store
(Node, Index)pairs in the Queue. - 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.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution Code
- Complexity Analysis
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.
