Zigzag Level Order

35 min · zigzagLevelOrder()

Picture ushers checking theater rows: they cross the first row left to right, turn around for the next, then keep switching direction without skipping a seat.

Given the root of a binary tree, return its values one level at a time in zigzag order — alternating the reading direction on each depth. Read depth 0 from left to right, depth 1 from right to left, depth 2 from left to right, and so on.

Keep these rules straight:

  • Return one inner array per depth, ordered from the root downward.
  • Switching direction changes only the output order; it doesn't change the tree.
  • Return [] for an empty tree.

Constraints

  • 0 <= node count <= 10_000
  • -1_000 <= node.val <= 1_000

Hints

Separate collecting from turning

First collect every level from left to right. Once that works, reverse the arrays at odd-numbered depths.

Freeze the current level

Save the queue length before processing a level. Children can join the queue, but only the saved number of nodes belongs in the current inner array.

Track one bit of state

A boolean can tell you whether the current level keeps its order or reverses. Flip it after finishing the whole level, not after every node.

Follow-up

Can you collect the same levels with depth-first traversal first, then apply the alternating reversals afterward?

Visible cases

Examples

Example 1

ready
Input
root = [
  3,
  9,
  20,
  null,
  null,
  15,
  7
]
Expected
[
  [
    3
  ],
  [
    20,
    9
  ],
  [
    15,
    7
  ]
]
Why
the middle level reverses, then the direction switches back

Example 2

ready
Input
root = []
Expected
[]
Why
an empty tree has no levels

Example 3

ready
Input
root = [
  1
]
Expected
[
  [
    1
  ]
]
Why
a single level reads left to right

Interview signal

Asked at

AmazonMetaMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite