Binary Tree Zigzag Level Order Traversal
Medium
Topics
Given the root of a binary tree, list its values level by level, alternating direction: the root level is read left to right, the next level right to left, the one after that left to right again, and so on. Return a list of levels, each a list of values. On this judge the levels are printed separated by |, and an empty tree prints an empty line.
Example 1
levels read right to left
Direction alternates per level, so the shaded levels are emitted right to left. The traversal itself stays a normal level-order walk — only the output order of each level flips, so reversing alternate rows is enough and no backwards traversal is needed.
Tree given in level-order (breadth-first);
null marks a missing child.Input: root = [1,2,3,4,5,6,7] Output: [[1],[3,2],[4,5,6,7]]
Example 2
levels read right to left
Input: root = [9,null,4,8] Output: [[9],[4],[8]]
Example 3
empty tree
Input: root = [] Output: []
Constraints
- 0 <= number of nodes <= 2000
- -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
The set of nodes on each level is exactly what a normal breadth-first traversal produces; only the order inside every other level changes. So run a plain level-order BFS and flip the odd-numbered levels before recording them.
Approach
- If the root is empty, return an empty list.
- BFS one level at a time: snapshot the queue length, pop that many nodes, collect their values and enqueue their children left then right.
- If the level index is odd, reverse the collected values (or fill them into a deque from the front).
- Append the level and continue.
Dry Run
tree 1 2 3 4 5 6 7
level in queue order [1] reverse=false record [1]
level in queue order [2, 3] reverse=true record [3, 2]
level in queue order [4, 5, 6, 7] reverse=false record [4, 5, 6, 7]
answer [1] | [3, 2] | [4, 5, 6, 7]
The queue is always built left to right. Only the RECORDED order alternates, and
that separation is the whole point: children are enqueued in a fixed order so the
next level's left-to-right sequence is always correct, and the reversal is applied
to the output list afterwards.
Flipping the enqueue order instead looks equivalent and is not. It gives
[[1], [3, 2], [5, 4, 7, 6]] -- level 2 is right, level 3 is wrong, because
reversing the parents' traversal order permutes their children in pairs rather
than reversing the level. The error compounds with depth, which is why it tends to
pass a two-level test and fail a three-level one.
`reverse` is flipped once per level, unconditionally. Guard the flip with
`if reverse:` and the flag can never leave false in the first place, so nothing
is ever reversed: the output becomes plain level order, [[1], [2, 3],
[4, 5, 6, 7]].Complexity
- Time — O(n): every node is enqueued and dequeued once; reversing a level is linear in its size.
- Space — O(n): the queue can hold a whole level.
Common Pitfalls
- Changing the order you enqueue children instead of the order you record values scrambles deeper levels.
- Alternating by a boolean that you forget to flip on every level, including levels you reverse.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def zigzagLevelOrder(self, root):
if not root:
return []
out = []
level = [root]
reverse = False
while level:
values = [node.val for node in level]
out.append(values[::-1] if reverse else values)
nxt = []
for node in level:
if node.left:
nxt.append(node.left)
if node.right:
nxt.append(node.right)
level = nxt
reverse = not reverse
return outimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> out = new ArrayList<>();
if (root == null) return out;
List<TreeNode> level = new ArrayList<>();
level.add(root);
boolean reverse = false;
while (!level.isEmpty()) {
List<Integer> values = new ArrayList<>();
for (TreeNode n : level) values.add(n.val);
if (reverse) Collections.reverse(values);
out.add(values);
List<TreeNode> next = new ArrayList<>();
for (TreeNode n : level) {
if (n.left != null) next.add(n.left);
if (n.right != null) next.add(n.right);
}
level = next;
reverse = !reverse;
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> out;
if (!root) return out;
vector<TreeNode*> level {
root
};
bool reverse_ = false;
while (!level.empty()) {
vector<int> values;
for (TreeNode* n : level) values.push_back(n->val);
if (reverse_) reverse(values.begin(), values.end());
out.push_back(values);
vector<TreeNode*> next;
for (TreeNode* n : level) {
if (n->left) next.push_back(n->left);
if (n->right) next.push_back(n->right);
}
level = next;
reverse_ = !reverse_;
}
return out;
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @return {number[][]}
*/ var zigzagLevelOrder = function(root) {
if (!root) return [];
const out = [];
let level = [root], reverse = false;
while (level.length) {
const values = level.map(n => n.val);
out.push(reverse ? values.slice().reverse() : values);
const next = [];
for (const node of level) {
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
level = next;
reverse = !reverse;
}
return out;
};