Given the root of a binary tree, return the zigzag level order traversal of its nodes' values (i.e., from left to right, then right to left for the next level, alternating).
root = [3,9,20,null,null,15,7][[3],[20,9],[15,7]]root = [1,2,3,4,5][[1],[3,2],[4,5]]root = [1][[1]]leftToRight = truesz = queue.size(); create LinkedList<Integer> leveladdLast(val) if L→R, addFirst(val) if R←L; enqueue children left→rightleftToRight = !leftToRightChildren are always enqueued left→right, so the queue order never changes. The trick is how we insert into the level list. For L→R levels we call addLast(val) — values accumulate in natural order. For R←L levels we call addFirst(val) — each new value is prepended, reversing the order without any extra reversal pass. After every level we flip leftToRight = !leftToRight. One boolean, zero extra work — O(1) per node.
One way is to run a normal level order traversal, and then reverse every second level at the end. That is fine, but it touches some levels twice. We can place each value in its correct slot directly.
Run a normal breadth first search, one level per round. Keep a flag that says whether the current level goes left to right. For each level, create a list of exactly the level size. The k-th node popped goes to index k when going left to right, or to index size −1 minus k when going right to left. Flip the flag after every level.
Do not change the order you visit nodes, only where you write them. The index n −1 minus k reverses a level for free.
Run the animation above on your own input, or watch the 2:18 video explanation of Binary Tree Zigzag Level Order Traversal with a dry run and Java code.