Skip to content
Problem 103 · LeetCode 103(opens in a new tab)

Binary Tree Zigzag Level Order Traversal

MediumBreadth-first search

You are given the root of a binary tree. List its values level by level, top to bottom, but change direction on every level: the top level reads left to right, the next right to left, the one after left to right again, and so on.

Return one list per level. An empty tree gives an empty list.

Example 1

Input:  root = [5, 1, 8, 4, null, 2, 6]
Output: [[5], [8, 1], [4, 2, 6]]
Why:    the middle level is read right to left
2 more examples and the constraints

Example 2

Input:  root = [7]
Output: [[7]]
Why:    one level with one node

Example 3

Input:  root = []
Output: []
Why:    no nodes, no levels

Constraints

  • 0 ≤ number of nodes ≤ 2,000
  • −100 ≤ node value ≤ 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Level order, then reverseO(n)
  2. Place by indexO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 2,000 nodesVerdict
Level order, then reverseO(n)
Passes; easy to explain
Place by indexO(n)
Best; each value written once

n = number of nodes, w = width of the widest level.

Edge cases to test

  • Empty tree. root = [] gives [], not [[]].
  • One node. [7] gives [[7]]; the direction never matters.
  • A chain. One node per level, so every row has one value and flipping changes nothing.
  • Gaps in a level. Missing children are simply not queued; the row is as long as the nodes that exist.

Common mistakes

  • Pushing the right child before the left on odd levels: the order of the next level gets scrambled.
  • Reading the queue length inside the inner loop while children are being added.
  • Starting right to left at the root, so every row comes out mirrored.

How to talk through it

  1. 1Clarify. Top level left to right? What should an empty tree return?
  2. 2Start from level order. A BFS where the queue size marks one level. That gives the rows, only some in the wrong order.
  3. 3Give the simple fix. Reverse every odd row. Still O(n).
  4. 4Code the index trick. Keep the queue order and write the i-th value to size − 1 − i on reversed levels.
  5. 5Test out loud. Run the empty tree, one node, and Example 1, checking the middle row.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?