#662

Maximum Width of Binary Tree

Medium BFS with position indexes

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

The width of a level is the distance between its leftmost and rightmost non-null nodes, counting the null gaps in between. Return the maximum width.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the widest level, counting the gaps between the end nodes.

Why this works: number nodes like a heap (children 2i and 2i+1). Width = last index - first index + 1.

Example: 1 (3 (5, 3), 2 (-, 9))

last level indexes 0, 1, 3 → width 3 - 0 + 1 = 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Letting indexes double every level — they overflow on deep skewed trees.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(w).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon