Binary Tree Zigzag Level Order Traversal

medium

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.

Hints

Run a normal level-order BFS and keep a direction flag that flips each level.
Collect each level left-to-right, then reverse the rows on odd levels.
The traversal (enqueue left then right) never changes — only the row layout does.

Common doubts

No — keep enqueuing left-then-right; only reverse the collected row for odd levels, or place values positionally.
Level 0 (the root) is left-to-right; the direction alternates from there.
Use a deque per level and front-insert on right-to-left levels, or write each value to index size-1-i.

Interview follow-ups

Alternate pushing children left-first vs right-first onto two stacks — a classic stack-based zigzag.
Only the odd levels are reversed; everything else is identical.

Fun facts

  • Zigzag order is also called 'spiral' or 'boustrophedon' traversal, after the ox-plowing pattern of ancient writing.
  • You can implement it with two stacks instead of a flag, alternating the child push order.

Asked at

AmazonMicrosoftFacebook
Frequently Sometimes Occasionally
Example 1
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.
Example 2
Input: root = [1]
Output: [[1]]
A single node forms one level.
Example 3
Input: root = []
Output: []
An empty tree has no levels.
Constraints

- The number of nodes is in the range [0, 2000] - -100 <= Node.val <= 100

Solve this problem →