Binary Tree Zigzag Level Order Traversal (LeetCode 103): Solution and Explanation

Medium
Tree
Breadth First Search
Binary Tree

Return the values of a binary tree level by level, but alternate the direction: the first level reads left to right, the second right to left, the third left to right again, and so on.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Strip away the zigzag and this is ordinary level-order traversal, which a queue handles cleanly. You take the queue's size at the start of each round, pop that many nodes, record their values, and push their children. Each round produces one level from left to right.

The zigzag only changes how each level is presented, not which nodes belong to it. That suggests the simplest fix: keep the traversal exactly the same, and when a finished level should read right to left, reverse it before adding it to the answer.

How do you know which levels to flip? The number of levels already in the result tells you. When len(res) is odd, you are about to append the second, fourth or sixth level, which are the ones that read right to left.

It is tempting to try to change the order in which children are enqueued instead, but that scrambles the order of the following level and quickly becomes confusing. Reversing a finished list costs time proportional to its length, so over the whole tree it adds only O(n) work and keeps the traversal itself untouched.

Approach: BFS with alternate level reversal

  1. Create an empty result res and a deque that holds the root, or nothing if the tree is empty.
  2. While the queue is not empty, start an empty list level for the current round.
  3. Loop len(q) times: pop a node, append its value to level, and enqueue its left child and then its right child if they exist.
  4. If len(res) is odd, reverse level so it reads right to left.
  5. Append level to res, and return res after the queue empties.

Step-by-step example

root = [3,9,20,null,null,15,7]
  1. The queue starts as [3]. The first round pops 3 and enqueues 9 and 20. The level is [3], and len(res) is 0, so there is no reversal. The result is [[3]].
  2. The second round pops 9, which has no children, and then 20, which enqueues 15 and 7. The level is [9,20].
  3. Now len(res) is 1, which is odd, so the level is reversed to [20,9]. The result is [[3],[20,9]].
  4. The third round pops 15 and 7, which have no children. The level is [15,7], and len(res) is 2, so it stays as is.
  5. The queue is empty, so the answer is [[3],[20,9],[15,7]].

Code: Python, Java, C++

1class Solution:
2    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
3        res = []
4        q = deque([root] if root else [])
5        
6        while q:
7            level = []
8            for i in range(len(q)):
9                node = q.popleft()
10                level.append(node.val)
11                if node.left:
12                    q.append(node.left)
13                if node.right:
14                    q.append(node.right)
15            
16            if len(res) % 2 == 1:
17                level.reverse()
18                
19            res.append(level)
20            
21        return res

Time and space complexity

Time

O(n)

Each node is enqueued and dequeued once. Reversing a level costs time proportional to its size, and the level sizes add up to n, so reversals contribute O(n) in total.

Space

O(n)

The queue can hold an entire level, which is up to about n / 2 nodes in a complete tree, and the output itself stores all n values.

Other approaches

Deque per level (time O(n), space O(n))

Build each level in a deque. On left-to-right levels append values to the right, and on right-to-left levels append them to the left. The traversal order stays normal and no reversal is needed, though the asymptotic cost is the same.

Two stacks (time O(n), space O(n))

Keep one stack for the current level and one for the next. Pop from the current stack and push children in left-then-right order on one level and right-then-left on the next. The stacks naturally produce the zigzag order without any reversal.

Common mistakes

  • Using len(q) as the loop bound after children have started being appended, which mixes two levels together. Python's range(len(q)) evaluates once, but a while loop that rechecks the length does not.
  • Reversing the even-indexed levels instead of the odd ones, which flips the root level and gets every direction backward.
  • Swapping the order in which children are enqueued on alternate levels. That breaks the order of the level after it.
  • Putting None into the queue for an empty tree and then reading node.val. Start with an empty queue when there is no root.

Frequently asked questions

Is reversing each level inefficient?

No. Each node is reversed at most once, so all reversals together cost O(n), the same as the traversal. The total time stays linear.

Can zigzag level order be done with DFS?

Yes. Pass the depth into a recursive DFS, and when appending a value to res[depth], add it at the end for even depths and at the front for odd depths. Inserting at the front of a Python list is slow, so use a deque for each level if you go this way.

How do you know which direction a level should go?

Count the levels already in the result. If that count is even the new level reads left to right, and if it is odd it reads right to left.