Given the root of a binary tree, return the zigzag level order traversal of its node values. Even-depth levels are traversed left to right; odd-depth levels are traversed right to left.

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Explanation: Level 0 (L→R): [3]. Level 1 (R→L): [20,9]. Level 2 (L→R): [15,7].
Input: root = [1]
Output: [[1]]
Constraints:

Contents

BFS with Direction Flag

Standard BFS with a boolean leftToRight flag. For each level, collect the node values in a LinkedList. When the flag is true, append values to the tail (left-to-right order); when false, prepend values to the head (right-to-left order). Toggle the flag after each level. Children are always enqueued left-before-right.

Algorithm:
public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); boolean leftToRight = true; while (!queue.isEmpty()) { int levelSize = queue.size(); LinkedList<Integer> level = new LinkedList<>(); for (int i = 0; i < levelSize; i++) { TreeNode node = queue.poll(); if (leftToRight) { level.addLast(node.val); } else { level.addFirst(node.val); // prepend for R→L } if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } result.add(level); leftToRight = !leftToRight; // toggle direction } return result; }
Trace through Example 1: root = [3,9,20,null,null,15,7]
LevelDirectionNodesLevel output
0L→R3[3]
1R→L9, 20[20, 9]
2L→R15, 7[15, 7]