Given the root of a binary tree, return the zigzag level-order traversal of its nodes' values — level by level, but alternating direction: left-to-right on the first level, right-to-left on the next, and so on.
The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [3, 9, 20, null, null, 15, 7] Output: [[3], [20, 9], [15, 7]] Level 0 left-to-right, level 1 right-to-left, level 2 left-to-right.
Input: root = [1] Output: [[1]] A single node forms one level.
Input: root = [] Output: [] An empty tree has no levels.
- The number of nodes is in the range [0, 2000] - -100 <= Node.val <= 100
Zigzag order is ordinary level-order with one extra rule: reverse every other level. Do a normal breadth-first traversal to collect each level left-to-right, then flip the rows at odd levels. A left-to-right flag toggled each level is all the bookkeeping you need.
“Which level goes which way?”
The first (level 0) is left-to-right; then it alternates.
“Empty tree?”
Return an empty list.
I run a normal level-order BFS and keep a left-to-right flag that flips each level.
When the flag says right-to-left, I reverse that level's row before adding it.
Worked example — tree [3, 9, 20, null, null, 15, 7]
3
/ \
9 20
/ \
15 7
level 0 (L->R): [3]
level 1 (R->L): [20, 9]
level 2 (L->R): [15, 7]
result: [[3], [20, 9], [15, 7]]
Collect each level normally; only the direction of odd levels changes.
The BFS still enqueues left-then-right; the zigzag lives entirely in how you lay out each row.
Each node is visited once and each row reversed once — O(n) overall.
| Index placement (deque/positional) | Reverse alternate rows | |
|---|---|---|
| Idea | Insert at front or compute mirrored index per node | Collect L->R, reverse odd levels |
| Time | O(n) | O(n) |
| Space | O(n) | O(n) |
Both are O(n); reversing alternate rows is the simplest to write. Full code is in the Approaches selector below.
Key takeaway
Run level-order BFS and reverse every other level. A per-level direction flag decides which rows to flip. O(n) time and space.
zigzag(root):
bfs level by level, collecting each row L->R
if the level index is odd: reverse the row
append the row