#103

Binary Tree Zigzag Level Order Traversal

Medium BFS with alternating direction

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

?The problem

Return level-order values, but alternate direction each level: left-to-right, then right-to-left, and so on.

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

◎Understanding

Really asking: level order, but alternating left-to-right and right-to-left.

Why this works: normal BFS; on odd levels add values to the front of the level list.

Example: 3 (9, 20 (15, 7))

[3], [20, 9], [15, 7]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Changing the order you push children into the queue — that scrambles the next levels.

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