LeetCode #103 Medium

Zigzag Level Order Traversal

Binary Tree Zigzag Level Order Traversal is LeetCode 103 (Medium). Given the root of a binary tree, return its values level by level, reading the first level left to right, the next right to left, and so on.

  • The tree can be empty; then the answer is [].
  • It has up to 2000 nodes, so one O(n) pass is all that is needed.
Constraints
  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100
treebfs
Open on LeetCode ↗
02

Intuition

Which nodes sit on a level does not depend on the reading direction; only their order inside the row does. So the zigzag order is an ordinary level-by-level BFS with one change at the end of each level:

  • Even levels (0, 2, …): save the row as collected, left to right.
  • Odd levels (1, 3, …): reverse the row, then save it.

The queue itself always works left to right, so every level is collected correctly, and only the finished row is flipped. A flag that changes after each level says which case applies.

How to spot this pattern

Any by-level output with a twist, such as zigzag rows, the right side view, level averages or the largest value per row, starts from the same BFS that reads len(queue) at the start of each level. The twist is applied to the finished row, not to the queue.

03

Approach

Try it first

Before reading on: for [1,2,3,4,5,6,7] the answer is [[1], [3, 2], [4, 5, 6, 7]]. If you enqueued 3 before 2 to read level 1 backwards, in which order would their children come out on level 2?

1

Start a queue with the root

Return [] for an empty tree. Otherwise put the root in a queue and set left_to_right = True, because level 0 is read left to right.

2

Take one whole level

Read len(queue) before the inner loop: that is the number of nodes on the current level. Take exactly that many from the front, append each value to level, and enqueue the node's left child, then its right child. The children belong to the next level and wait behind the current nodes.

3

Reverse every second row

If left_to_right is false, reverse level. Then append it to the result and flip the flag. Only the finished row is reversed; the queue still holds the next level left to right, so that level is collected correctly too.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
▶3 if not root:
▶4 return []
▶5 result, queue = [], deque([root])
▶6 left_to_right = True
▶7 while queue:
▶8 level = []
▶9 for _ in range(len(queue)):
▶10 node = queue.popleft()
▶11 level.append(node.val)
▶12 if node.left:
▶13 queue.append(node.left)
▶14 if node.right:
▶15 queue.append(node.right)
▶16 if not left_to_right:
▶17 level.reverse()
▶18 result.append(level)
▶19 left_to_right = not left_to_right
▶20 return result
takenin queue3920157queue3frontlevelemptyresultemptyqueue starts with the root
queue[3]
left_to_rightTruelevel 0 reads left to right
Start with the root in the queue. The queue always works left to right; the direction flag starts true because level 0 is read left to right.
takenin queue3920157queue9front20level3resultemptytake 3, queue 9 and 20
node3node 1 of 1 on level 0
level[3]
queue[9, 20]front on the left
Level 0 has 1 node, the queue length when the level starts, so exactly 1 will be taken. Take 3 from the front and add it to the level. Its children 9 and 20 go to the back of the queue, left first; they belong to the next level and wait behind this one.
takenin queue3920157queue9front20level3left → rightresult3save [3], flip direction
result[[3]]
left_to_rightFalsefor level 1
Level 0 is read left to right, so the row is saved as collected. Then flip the flag, so level 1 will be read right to left.
takenin queue3920157queue20frontlevel9result3take 9, no children
node9node 1 of 2 on level 1
level[9]
queue[20]front on the left
Level 1 has 2 nodes, the queue length when the level starts, so exactly 2 will be taken. Take 9 from the front and add it to the level. It has no children, so the queue only shrinks.
takenin queue3920157queue15front7level920result3take 20, queue 15 and 7
node20node 2 of 2 on level 1
level[9, 20]
queue[15, 7]front on the left
Take 20, node 2 of 2 on this level, and add it to the level. Its children 15 and 7 go to the back of the queue, left first; they belong to the next level and wait behind this one.
takenin queue3920157queue15front7level209right → leftresult3odd level → reverse to [20, 9]
collected[9, 20]left to right, as the queue gave it
level[20, 9]reversed
left_to_rightFalse
Level 1 is read right to left, so reverse the finished row. Only this row is flipped; the queue still holds the next level in left-to-right order, so that level is collected correctly.
takenin queue3920157queue15front7level209right → leftresult3209save [20, 9], flip direction
result[[3], [20, 9]]
left_to_rightTruefor level 2
Save the reversed row. Then flip the flag, so level 2 will be read left to right.
takenin queue3920157queue7frontlevel15result3209take 15, no children
node15node 1 of 2 on level 2
level[15]
queue[7]front on the left
Level 2 has 2 nodes, the queue length when the level starts, so exactly 2 will be taken. Take 15 from the front and add it to the level. It has no children, so the queue only shrinks.
takenin queue3920157queueemptylevel157result3209take 7, no children
node7node 2 of 2 on level 2
level[15, 7]
queue[]front on the left
Take 7, node 2 of 2 on this level, and add it to the level. It has no children, so the queue only shrinks.
takenin queue3920157queueemptylevel157left → rightresult3209157save [15, 7], flip direction
result[[3], [20, 9], [15, 7]]
left_to_rightFalsefor level 3
Level 2 is read left to right, so the row is saved as collected. Then flip the flag, so level 3 will be read right to left. The queue is empty, so this was the last level.
takenin queue3920157queueemptylevelemptyresult3209157queue empty → return 3 rows
result[[3], [20, 9], [15, 7]]
work5 nodes taken onceO(n)
Done. Every node went through the queue once, and every second row was reversed after it was collected, giving the zigzag order.
05

Common pitfalls

Switching the order children are enqueued

✗ Wrong
if left_to_right:
    queue.append(node.right)
    queue.append(node.left)
else:
    queue.append(node.left)
    queue.append(node.right)
✓ Right
if node.left:
    queue.append(node.left)
if node.right:
    queue.append(node.right)
...
if not left_to_right:
    level.reverse()

Level 1 comes out right, [3, 2], but then 3's children are queued before 2's, so level 2 is [6, 7, 4, 5] instead of [4, 5, 6, 7]. Swapping the child order only flips each pair of siblings; it does not reverse the whole row.

Not fixing the level size before the loop

✗ Wrong
while queue:
    node = queue.popleft()
    level.append(node.val)
✓ Right
for _ in range(len(queue)):
    node = queue.popleft()
    level.append(node.val)

Children are added while the level is being read, so a loop that runs until the queue is empty swallows every level into one row. range(len(queue)) is evaluated once, before any child is added.

06

Complexity

Time
O(n)
Space
O(w)
Each node passes through the queue once, and each reversal touches a value at most once more. The queue holds at most one level plus part of the next, so the space is O(w), where w is the widest level, up to about n/2.
07

Zigzag Level Order Traversal FAQ

Is GFG ZigZag Tree Traversal the same problem?

Nearly. The GeeksforGeeks version returns one flat list instead of one list per level, so extend a single list with each row. Its older spiral order problem reverses the opposite levels, so check whether the second row in the example is read left to right.

Can each row be built in order without reversing it?

Yes. Create the row with size empty slots and write the i-th node taken to index i on left-to-right levels and to size - 1 - i on the others; a deque with appendleft does the same. Another version keeps two stacks, one per direction. All are O(n), the same as reversing.