Skip to content
StackDecode
TreesAnimated

Zigzag Traversal

Level order that reverses direction on alternate rows.

Time

O(n)

Extra space

O(w)

Use it for

Spiral printing of a tree.

How it works

  1. Do a level-order traversal, one whole row at a time.
  2. Read the first row left to right, the second row right to left, and keep alternating.
  3. A flag flips after every row. O(n).

Watch it run

Loading animation…