Binary Tree Zigzag Level Order Traversal (LeetCode 103): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Create an empty result
resand a deque that holds the root, or nothing if the tree is empty. - While the queue is not empty, start an empty list
levelfor the current round. - Loop
len(q)times: pop a node, append its value tolevel, and enqueue its left child and then its right child if they exist. - If
len(res)is odd, reverselevelso it reads right to left. - Append
leveltores, and returnresafter the queue empties.
Step-by-step example
root = [3,9,20,null,null,15,7]
- 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]]. - The second round pops 9, which has no children, and then 20, which enqueues 15 and 7. The level is [9,20].
- Now
len(res)is 1, which is odd, so the level is reversed to [20,9]. The result is [[3],[20,9]]. - 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. - 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 res1class Solution {
2 public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
3 List<List<Integer>> res = new ArrayList<>();
4 if (root == null) return res;
5
6 Queue<TreeNode> q = new LinkedList<>();
7 q.add(root);
8
9 while (!q.isEmpty()) {
10 List<Integer> level = new ArrayList<>();
11 int count = q.size();
12
13 for (int i = 0; i < count; i++) {
14 TreeNode node = q.poll();
15 level.add(node.val);
16 if (node.left != null) q.add(node.left);
17 if (node.right != null) q.add(node.right);
18 }
19
20 if (res.size() % 2 == 1) {
21 Collections.reverse(level);
22 }
23
24 res.add(level);
25 }
26
27 return res;
28 }
29}1class Solution {
2public:
3 vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
4 vector<vector<int>> res;
5 if (!root) return res;
6
7 queue<TreeNode*> q;
8 q.push(root);
9
10 while (!q.empty()) {
11 vector<int> level;
12 int count = q.size();
13
14 for (int i = 0; i < count; i++) {
15 TreeNode* node = q.front();
16 q.pop();
17 level.push_back(node->val);
18 if (node->left) q.push(node->left);
19 if (node->right) q.push(node->right);
20 }
21
22 if (res.size() % 2 == 1) {
23 reverse(level.begin(), level.end());
24 }
25
26 res.push_back(level);
27 }
28
29 return res;
30 }
31};Time and space complexity
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.
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'srange(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
Noneinto the queue for an empty tree and then readingnode.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.