Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Zigzag Level Order

LeetCode #103Medium
Alternate L→R, R→L each level

Given the root of a binary tree, return its zigzag level-order traversal: collect node values level by level, alternating direction left-to-right then right-to-left on each successive level.

Asked atAmazonMicrosoftLinkedIn
step 1 / 14
binary tree
9
3
15
20
7
queue (FIFO)
front →
(empty)
← back
BFS + direction flag
1zigzag(root):
2 queue = [root]; leftToRight = true
3 while queue not empty:
4 levelSize = len(queue)
5 collected = []
6 for _ in range(levelSize):
7 node = queue.dequeue()
8 collected.append(node.val)
9 enqueue node.children
10 result.append(collected if leftToRight else reversed(collected))
11 leftToRight = not leftToRight
12 return result
state
  • targetsnake by level
  • leftToRighttrue

line 1LeetCode 103 — zigzag level order. Read level 0 left→right, level 1 right→left, level 2 left→right, and so on, snaking down the tree. The BFS stays the same (always enqueue left then right); we only flip how we ORDER the collected values, tracked by a direction flag.