15% off all plans & roadmaps Use code
See plansBinary Tree Zigzag Level Order Traversal
- LeetCode 103
- Medium
- Tree Traversal Patterns (DFS & BFS)
- Level Order Traversal
Updated
TL;DR: Return the values of a binary tree level by level, reversing the direction of every other level. Run a breadth-first search, then write each level's values into fixed slots so the odd levels come out right to left in one pass.
Problem
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. That means you read the first level from left to right, the second level from right to left, the third from left to right, and so on.
Example 1
Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]]
Example 2
Input: root = [1] Output: [[1]]
Example 3
Input: root = [] Output: []
Constraints
- The number of nodes in the tree is in the range
[0, 2000]. -100 <= Node.val <= 100
Constraints that matter
- With up to 2000 nodes, a skewed tree can have 2000 levels. That makes O(N * H) work possible, and O(N^2) is the worst case you should expect from a rescan-per-level idea.
- Values range from -100 to 100, but the answer depends only on the tree's shape. Ignore the values when you decide the order.
- The output holds every node once, so any correct solution must touch all N nodes. O(N) time is the floor.
- A chain of 2000 nodes means recursion can go 2000 frames deep. Python's default limit is 1000, so the Python code below uses an explicit stack or queue.
Hints
Hint 1
The problem asks for levels.
Hint 2
The naive approach finds the answer one level at a time.
Solution
Intuition
The problem asks for levels. A level is the set of nodes at one depth, and that points to breadth-first search (level order traversal). A queue hands you the nodes one depth at a time, so you never have to find a level by searching for it.
Picture a row of numbered mailboxes, one per node, labeled before any letter arrives. Letters come in left to right, but on odd levels each goes into the box counted from the far end.
The zigzag is a rule about output, not about traversal. Children still enter the queue left first, so each level keeps its true left-to-right geometry. If you flipped the child order on odd levels, the next level would come out scrambled.
That leaves one question: how do you write a level backwards without reversing it? The queue yields the i-th node of a level at position i from the left. On a right-to-left level, that node belongs in slot size minus 1 minus i. Allocate the level array first, and no reversal or front insertion is needed.
Worked example
Input: root = [3, 9, 20, null, null, 15, 7] Output: [[3], [20, 9], [15, 7]] Explanation: The tree has three levels. Level 0 holds 3, which reads left to right as [3]. Level 1 holds 9 and 20 in left-to-right order, but it must read right to left, so it becomes [20, 9]. Level 2 holds 15 and 7 and reads left to right as [15, 7].
Approach 1: Brute force (rescan the tree for each level)
The naive approach finds the answer one level at a time. It first measures the tree's height. Then, for each level, it walks the whole tree and collects only the nodes at that depth, in left-to-right order. Odd levels get reversed before they are stored.
What's slow: the walk repeats work. A node at depth d is visited once for every level from 0 to H, so the upper part of the tree gets scanned again and again. On a skewed tree with 2000 nodes, the same chain is rescanned 2000 times. The insight that is worth keeping is that the left-to-right order at each depth is already correct, so the scan only needs to be done once if you keep all levels at once.
Steps
- Return an empty list when
rootis null. - Find the height H with a stack that tracks each node's depth. Keep the largest depth seen.
- For each level from 0 to H minus 1, start a new stack at the root with depth 0.
- Pop nodes. Store a value when its depth equals the level. Push children only while the depth is less than the level, pushing right first so left pops first.
- If the level is odd, reverse its values.
- Append the level's values to the result and return the result after the last level.
Dry run
The tree has height 3, so the outer loop runs for levels 0, 1, and 2.
Level 0: the scan finds 3 at depth 0. The level is [3]. It is even, so it stays [3].
Level 1: the scan finds 9 and then 20, which is left-to-right order. The level is [9, 20]. It is odd, so it reverses to [20, 9].
Level 2: the scan finds 15 and then 7. The level is [15, 7]. It is even, so it stays.
Result: [[3], [20, 9], [15, 7]].
Complexity
| Time | O(N * H), which is O(N^2) on a skewed tree |
|---|---|
| Space | O(H) for the explicit stack, plus the O(N) output |
Let N be the number of nodes and H the height. The height pass visits each node once, which is O(N). The outer loop runs H times, and each run walks every node once, which adds up to O(N * H).
Since H is at most N, the worst case is a chain, where H equals N and the total is O(N^2). The stack holds at most one pending sibling per level on the current path, so it stays at O(H) entries.
PythonTested in our runner
from typing import List, Optional
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
# Pass 1: find the number of levels with an explicit stack.
height = 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
height = max(height, depth)
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
result = []
# Pass 2 for each level: rescan the whole tree.
for level in range(height):
nodes = []
stack = [(root, 0)]
while stack:
node, depth = stack.pop()
if depth == level:
nodes.append(node.val)
elif depth < level:
# Push right first so the left child is popped first.
if node.right:
stack.append((node.right, depth + 1))
if node.left:
stack.append((node.left, depth + 1))
if level % 2 == 1:
nodes.reverse()
result.append(nodes)
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] zigzagLevelOrder(TreeNode root) {
if (root == null) return new int[0][];
// Pass 1: find the number of levels.
int height = 0;
Deque<TreeNode> nodes = new ArrayDeque<>();
Deque<Integer> depths = new ArrayDeque<>();
nodes.push(root);
depths.push(1);
while (!nodes.isEmpty()) {
TreeNode node = nodes.pop();
int depth = depths.pop();
height = Math.max(height, depth);
if (node.left != null) { nodes.push(node.left); depths.push(depth + 1); }
if (node.right != null) { nodes.push(node.right); depths.push(depth + 1); }
}
int[][] result = new int[height][];
// Pass 2 for each level: rescan the whole tree.
for (int level = 0; level < height; level++) {
List<Integer> values = new ArrayList<>();
nodes.push(root);
depths.push(0);
while (!nodes.isEmpty()) {
TreeNode node = nodes.pop();
int depth = depths.pop();
if (depth == level) {
values.add(node.val);
} else if (depth < level) {
// Push right first so the left child is popped first.
if (node.right != null) { nodes.push(node.right); depths.push(depth + 1); }
if (node.left != null) { nodes.push(node.left); depths.push(depth + 1); }
}
}
if (level % 2 == 1) Collections.reverse(values);
result[level] = new int[values.size()];
for (int i = 0; i < values.size(); i++) result[level][i] = values.get(i);
}
return result;
}
}
C++Tested in our runner
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
if (!root) return result;
// Pass 1: find the number of levels.
int height = 0;
vector<pair<TreeNode*, int>> stack;
stack.push_back(make_pair(root, 1));
while (!stack.empty()) {
pair<TreeNode*, int> top = stack.back();
stack.pop_back();
TreeNode* node = top.first;
int depth = top.second;
height = max(height, depth);
if (node->left) stack.push_back(make_pair(node->left, depth + 1));
if (node->right) stack.push_back(make_pair(node->right, depth + 1));
}
// Pass 2 for each level: rescan the whole tree.
for (int level = 0; level < height; level++) {
vector<int> values;
stack.push_back(make_pair(root, 0));
while (!stack.empty()) {
pair<TreeNode*, int> top = stack.back();
stack.pop_back();
TreeNode* node = top.first;
int depth = top.second;
if (depth == level) {
values.push_back(node->val);
} else if (depth < level) {
// Push right first so the left child is popped first.
if (node->right) stack.push_back(make_pair(node->right, depth + 1));
if (node->left) stack.push_back(make_pair(node->left, depth + 1));
}
}
if (level % 2 == 1) reverse(values.begin(), values.end());
result.push_back(values);
}
return result;
}
};
JavaScriptTested in our runner
var zigzagLevelOrder = function(root) {
const result = [];
if (!root) return result;
// Pass 1: find the number of levels.
let height = 0;
let stack = [{ node: root, depth: 1 }];
while (stack.length > 0) {
const top = stack.pop();
height = Math.max(height, top.depth);
if (top.node.left) stack.push({ node: top.node.left, depth: top.depth + 1 });
if (top.node.right) stack.push({ node: top.node.right, depth: top.depth + 1 });
}
// Pass 2 for each level: rescan the whole tree.
for (let level = 0; level < height; level++) {
const values = [];
stack = [{ node: root, depth: 0 }];
while (stack.length > 0) {
const top = stack.pop();
if (top.depth === level) {
values.push(top.node.val);
} else if (top.depth < level) {
// Push right first so the left child is popped first.
if (top.node.right) stack.push({ node: top.node.right, depth: top.depth + 1 });
if (top.node.left) stack.push({ node: top.node.left, depth: top.depth + 1 });
}
}
if (level % 2 === 1) values.reverse();
result.push(values);
}
return result;
};
GoTested in our runner
func zigzagLevelOrder(root *TreeNode) [][]int {
result := [][]int{}
if root == nil {
return result
}
type entry struct {
node *TreeNode
depth int
}
// Pass 1: find the number of levels.
height := 0
stack := []entry{{root, 1}}
for len(stack) > 0 {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if top.depth > height {
height = top.depth
}
if top.node.Left != nil {
stack = append(stack, entry{top.node.Left, top.depth + 1})
}
if top.node.Right != nil {
stack = append(stack, entry{top.node.Right, top.depth + 1})
}
}
// Pass 2 for each level: rescan the whole tree.
for level := 0; level < height; level++ {
nodes := []int{}
stack = []entry{{root, 0}}
for len(stack) > 0 {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if top.depth == level {
nodes = append(nodes, top.node.Val)
} else if top.depth < level {
// Push right first so the left child is popped first.
if top.node.Right != nil {
stack = append(stack, entry{top.node.Right, top.depth + 1})
}
if top.node.Left != nil {
stack = append(stack, entry{top.node.Left, top.depth + 1})
}
}
}
if level%2 == 1 {
for i, j := 0, len(nodes)-1; i < j; i, j = i+1, j-1 {
nodes[i], nodes[j] = nodes[j], nodes[i]
}
}
result = append(result, nodes)
}
return result
}
C#Tested in our runner
public class Solution {
public int[][] zigzagLevelOrder(TreeNode root) {
if (root == null) return new int[0][];
// Pass 1: find the number of levels.
int height = 0;
var stack = new Stack<(TreeNode node, int depth)>();
stack.Push((root, 1));
while (stack.Count > 0) {
var top = stack.Pop();
height = Math.Max(height, top.depth);
if (top.node.left != null) stack.Push((top.node.left, top.depth + 1));
if (top.node.right != null) stack.Push((top.node.right, top.depth + 1));
}
int[][] result = new int[height][];
// Pass 2 for each level: rescan the whole tree.
for (int level = 0; level < height; level++) {
var values = new List<int>();
stack.Push((root, 0));
while (stack.Count > 0) {
var top = stack.Pop();
if (top.depth == level) {
values.Add(top.node.val);
} else if (top.depth < level) {
// Push right first so the left child is popped first.
if (top.node.right != null) stack.Push((top.node.right, top.depth + 1));
if (top.node.left != null) stack.Push((top.node.left, top.depth + 1));
}
}
if (level % 2 == 1) values.Reverse();
result[level] = values.ToArray();
}
return result;
}
}
The Level Order Traversal infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Level Order Traversal
Approach 2: One-pass BFS with index slots (optimal)OptimalLevel Order Traversal
What's slow: the brute force walks the tree once per level, so the same nodes are visited many times. The insight that fixes it is that a queue already yields every node exactly once, level by level. The only remaining problem is direction.
Each level's size is known before you start it. So you can write node i into slot i on left-to-right levels and into slot size minus 1 minus i on right-to-left levels. The reversal happens for free, and the queue keeps children in left-to-right order so later levels stay correct.
Why it is correct. Every node enters the queue exactly once, and each level's size is fixed before filling starts. The slot mapping is one-to-one, so every position receives exactly one value and none is overwritten or missed. Children enter left first, so each level keeps the tree's true left-to-right order.
Steps
- Return an empty list when
rootis null. Otherwise enqueuerootand setleftToRightto true. - While the queue is not empty, read the current level's size and allocate an array of that size.
- Dequeue exactly
sizenodes. For the i-th one, write its value to slot i ifleftToRightis true, or to slot size minus 1 minus i if it is false. - Enqueue each dequeued node's left child, then its right child, when they exist.
- After the level is full, append the array to the result and flip
leftToRight. - Return the result when the queue is empty.
Dry run
Each row is one dequeue. The level column shows the depth, and the slot column shows where the value goes.
| Step | Level | Node popped | Slot written | Level array after step | Queue after step |
|---|---|---|---|---|---|
| 1 | 0 | 3 | 0 | [3] | [9, 20] |
| 2 | 1 | 9 | 1 | [_, 9] | [20] |
| 3 | 1 | 20 | 0 | [20, 9] | [15, 7] |
| 4 | 2 | 15 | 0 | [15, _] | [7] |
| 5 | 2 | 7 | 1 | [15, 7] | [] |
Level 1 runs right to left, so its size is 2 and the slot for the i-th node is 1 minus i. Node 9 is i = 0, so it lands in slot 1. Node 20 is i = 1, so it lands in slot 0. The result is [[3], [20, 9], [15, 7]], and the queue is empty at step 5.
Complexity
| Time | O(N) |
|---|---|
| Space | O(N) for the queue and the output |
Let N be the number of nodes. Each node is enqueued once and dequeued once, and each dequeue does constant work, so the loop body runs N times in total. Writing a value into a slot is O(1), and the level arrays together hold N values. The queue holds at most one full level plus the next, which is at most about N/2 nodes in a full tree, so the auxiliary space is O(N).
PythonTested in our runner
from collections import deque
from typing import List, Optional
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
result = []
queue = deque([root])
left_to_right = True
while queue:
size = len(queue)
# Allocate the level first so slots can be filled in any order.
level = [0] * size
for i in range(size):
node = queue.popleft()
# Right-to-left levels fill their slots from the end.
index = i if left_to_right else size - 1 - i
level[index] = node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
left_to_right = not left_to_right
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] zigzagLevelOrder(TreeNode root) {
if (root == null) return new int[0][];
List<int[]> result = new ArrayList<>();
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
boolean leftToRight = true;
while (!queue.isEmpty()) {
int size = queue.size();
int[] level = new int[size];
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
// Right-to-left levels fill their slots from the end.
int index = leftToRight ? i : size - 1 - i;
level[index] = node.val;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
result.add(level);
leftToRight = !leftToRight;
}
return result.toArray(new int[0][]);
}
}
C++Tested in our runner
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
if (!root) return result;
queue<TreeNode*> q;
q.push(root);
bool leftToRight = true;
while (!q.empty()) {
int size = q.size();
vector<int> level(size);
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
// Right-to-left levels fill their slots from the end.
int index = leftToRight ? i : size - 1 - i;
level[index] = node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
result.push_back(level);
leftToRight = !leftToRight;
}
return result;
}
};
JavaScriptTested in our runner
var zigzagLevelOrder = function(root) {
const result = [];
if (!root) return result;
let queue = [root];
let leftToRight = true;
while (queue.length > 0) {
const size = queue.length;
const level = new Array(size);
const next = [];
for (let i = 0; i < size; i++) {
const node = queue[i];
// Right-to-left levels fill their slots from the end.
const index = leftToRight ? i : size - 1 - i;
level[index] = node.val;
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
result.push(level);
queue = next;
leftToRight = !leftToRight;
}
return result;
};
GoTested in our runner
func zigzagLevelOrder(root *TreeNode) [][]int {
result := [][]int{}
if root == nil {
return result
}
queue := []*TreeNode{root}
leftToRight := true
for len(queue) > 0 {
size := len(queue)
level := make([]int, size)
next := []*TreeNode{}
for i, node := range queue {
// Right-to-left levels fill their slots from the end.
index := i
if !leftToRight {
index = size - 1 - i
}
level[index] = node.Val
if node.Left != nil {
next = append(next, node.Left)
}
if node.Right != nil {
next = append(next, node.Right)
}
}
result = append(result, level)
queue = next
leftToRight = !leftToRight
}
return result
}
C#Tested in our runner
public class Solution {
public int[][] zigzagLevelOrder(TreeNode root) {
if (root == null) return new int[0][];
var result = new List<int[]>();
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
bool leftToRight = true;
while (queue.Count > 0) {
int size = queue.Count;
int[] level = new int[size];
for (int i = 0; i < size; i++) {
TreeNode node = queue.Dequeue();
// Right-to-left levels fill their slots from the end.
int index = leftToRight ? i : size - 1 - i;
level[index] = node.val;
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
}
result.Add(level);
leftToRight = !leftToRight;
}
return result.ToArray();
}
}
Common mistakes
level.insert(0, node.val)on a Python list or Java ArrayList for right-to-left levels. Front insertion shifts every existing value, so each level costs O(K^2). Write into a preallocated slot, or useappendlefton a deque.- Reversing or reordering the children before enqueuing them on odd levels, as in
queue.append(node.right)first. The queue then yields the next level in the wrong geometry, and every level below is wrong too. Keep children in left-then-right order always. - Reading
size = len(queue)after the children were already pushed. The count then includes the next level, and the loop pulls nodes from the wrong depth. Read the size once, before the inner loop. - Flipping
leftToRightinside the node loop instead of after the level. The direction changes mid-level, so some nodes of one level are written in the wrong slots. - Creating the
levellist outside thewhileloop. Every level then appends into one shared list, and the result comes out flat instead of nested. - Returning a
List<List<Integer>>in Java or C# when the starter signature isint[][]. Collect each level as anint[]and convert at the end, or the code will not compile against the runner.
Edge cases
rootis null: return an empty result,[]in Python and an empty array in the other languages.- A single node
[1]: one level with one slot, so the output is[[1]]. The direction flag does not matter for a single slot. - A chain of 2000 nodes that leans left or right: 2000 levels with one node each. The optimal code runs in O(N) time, while recursive code can overflow the stack in Python.
- Only left children, with values
[-1,-2,-3]as a left chain: the output is[[-1],[-2],[-3]]. Negative values need no special handling. - A full tree such as
[1,2,3,4,5,6,7]: the output is[[1],[3,2],[4,5,6,7]]. The widest level holds 4 nodes, which is the largest the queue gets here.
Follow-ups interviewers ask
- What if you must write it recursively?
- Pass the depth down as a parameter. At each node, append its value to
result[depth], creating the list when the depth is new. After the walk, reverse every odd level. The recursion goes as deep as the tree is tall, so a 2000-node chain needs 2000 frames. Java, C++, Go and C# handle that, but Python's default limit of 1000 does not, unless you raise the limit. - Can you do it with O(1) extra space?
- Not with the standard node type. The queue reaches about N/2 entries on a full tree, and the brute force keeps O(H) stack entries and pays O(N * H) time. If each node also had a next pointer to its neighbour on the same level, you could walk each level with O(1) extra space and write the zigzag in place. The output itself is still O(N).
- What if the tree is too large for memory?
- The output alone holds N values, so you cannot avoid O(N) output memory. You can avoid holding the whole tree in memory at once. If the tree is stored on disk with each depth written as one contiguous block, you read one depth at a time. Then only the widest level sits in memory, and you reverse it before writing it out.
Binary Tree Zigzag Level Order Traversal FAQ
What is the time complexity of Binary Tree Zigzag Level Order Traversal?
The optimal BFS runs in O(N) time, where N is the number of nodes. Each node is enqueued and dequeued once, and each step does constant work. The rescan-per-level brute force runs in O(N * H), which is O(N^2) for a skewed tree.
Why use breadth-first search for Binary Tree Zigzag Level Order Traversal?
The output is grouped by depth, and a queue visits nodes in exactly that order. Processing the queue one full level at a time gives you each level as a group. The zigzag then only changes where each value is written.
Can Binary Tree Zigzag Level Order Traversal be solved in O(1) extra space?
No, not with the standard node type. A level-by-level walk needs either a queue, which can hold about N/2 nodes, or repeated scans, which need stack space of O(H). Neighbour pointers at each level would remove that need, but the problem does not provide them.
Why does recursion fail in Python for a deep zigzag tree?
Python's default recursion limit is 1000 frames. A chain of 2000 nodes makes a recursive walk go 2000 frames deep, which raises a RecursionError. Use an explicit deque or stack, as the code on this page does.
Asked at
See which companies ask this — Pro
Related problems
- Binary Tree Level Order Traversal · same technique: Level Order Traversal
- Binary Tree Right Side View · same technique: Level Order Traversal
- Find Largest Value in Each Tree Row · same technique: Level Order Traversal
- Maximum Level Sum of a Binary Tree · same technique: Level Order Traversal
- Binary Tree Maximum Path Sum · next harder, same pattern
- Validate Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Construct Binary Tree from Preorder and Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Lowest Common Ancestor of a Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Kth Smallest Element in a BST · same pattern: Tree Traversal Patterns (DFS & BFS)
- Count Good Nodes in Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)