Intuition
Do a normal level-order (BFS) traversal, but reverse the order of values on every other level so the output snakes left-to-right, then right-to-left.
Explanation
Idea
Zigzag order is just level-order with a twist: even levels read left-to-right, odd levels right-to-left. So we do a standard breadth-first traversal collecting each level's values, and simply reverse the collected list on alternating levels. Nodes are always enqueued left child then right child — only the output order per level flips.
Algorithm
- BFS with a queue; keep a boolean
left_to_rightstartingTrue. - For each level, pop all
countnodes, collect their values (always enqueue children left-then-right). - If
left_to_rightisFalse, reverse the level's list before appending. - Flip
left_to_rightand continue.
Worked example: [3,9,20,null,null,15,7]
- Level 0 (L→R):
[3]. - Level 1 (R→L): collected
[9,20], reversed →[20,9]. - Level 2 (L→R):
[15,7].
Result: [[3],[20,9],[15,7]].
Complexity
- Time: O(n) — each node visited once.
- Space: O(n) for the queue and output.
Implementation
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
boolean leftToRight = true;
while (!q.isEmpty()) {
int count = q.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < count; i++) {
TreeNode node = q.poll();
level.add(node.val);
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
if (!leftToRight) {
Collections.reverse(level);
}
result.add(level);
leftToRight = !leftToRight;
}
return result;
}
}