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
- Do a level-order traversal, one whole row at a time.
- Read the first row left to right, the second row right to left, and keep alternating.
- A flag flips after every row. O(n).
Watch it run
Loading animation…