InterviewPrepKit

Home / Coding / Trees

Binary Tree Zigzag Level Order Traversal

medium Original ↗
Solving tips
  • This is plain BFS-by-level plus one twist: the visit order never changes, only the recording order flips per level.
  • Track a direction flag toggled once per level; use a deque and appendleft on reversed levels to build them in O(1) per element without a separate reverse pass.
  • Snapshot len(queue) before the inner loop, and toggle the direction outside the inner loop (once per level), not per node.
  • Don't reverse the node-visit order (e.g. enqueuing right first), which corrupts the next level; return [] not [[]] for an empty tree. Target O(n) time and space.

Problem

You are given the root of a binary tree. Return the values of its nodes grouped by level (depth), but with the direction alternating: the first level is listed left-to-right, the second level right-to-left, the third left-to-right again, and so on.

The answer is a list of lists — one inner list per level, ordered from the root level downward, with each inner list already in its zigzag direction.

Examples

Example 1

Input:  root = [3, 9, 20, null, null, 15, 7]

        3
       / \
      9   20
         /  \
        15   7

Output: [[3], [20, 9], [15, 7]]

Level 0 goes left-to-right ([3]), level 1 flips ([20, 9]), level 2 flips back ([15, 7]).

Example 2

Input:  root = [1, 2, 3, 4, 5, 6, 7]
Output: [[1], [3, 2], [4, 5, 6, 7]]

Odd-indexed levels are reversed; even-indexed levels keep natural order.

Example 3

Input:  root = []
Output: []

An empty tree produces an empty answer.

Constraints

  • The number of nodes is in the range [0, 2000].
  • -100 <= Node.val <= 100
  • Expected complexity: O(n) time — every node must be visited exactly once.

Think about it first

Hint 1 Do you already know how to produce a plain level-order traversal? Zigzag is that traversal plus one small twist.
Hint 2 Keep a flag (or use the level's index parity) telling you whether the current level should be reversed. You never need to change the order in which you *visit* nodes.
Hint 3 Standard BFS with a queue: pop one full level at a time into a list, then either append the list as-is or reversed depending on the level's parity. Alternatively, a deque lets you build each level in the correct order directly by choosing which end you write to.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.