CodingNodes / Trees / Binary Tree Zigzag Level Order Traversal System design Space play · ←→ step · R restart

Problem

Given the root of a binary tree, return its node values level by level, but alternate the reading direction: the first level left to right, the second right to left, the third left to right again, and so on.

The tree is given in level order, with null for a missing child. An empty tree gives an empty list.

Constraints

  • 0 ≤ number of nodes ≤ 2000
  • -100 ≤ Node.val ≤ 100

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(w)

Time: Every node is added to the queue once, taken out once, and written into the answer once.

Space: The queue holds at most one or two levels at a time, so it is as large as the widest level, w. That can reach n/2. The result itself holds n values.

Do the normal level by level BFS, which always queues children left then right. Only the writing changes: make an array of the level's size and put the i-th node in slot i going left to right, or in slot size - 1 - i going right to left. Flip the direction after each level. Nothing is ever reversed after the fact.