sagelearnai

Binary Tree Zigzag Level Order Traversal

Difficulty: Medium · Pattern: Trees & BST · LeetCode #103

Given the root of a binary tree, return the zigzag level-order traversal of its values: left-to-right on the first level, right-to-left on the next, and alternating from there.

Examples

text
[3,9,20,null,null,15,7]   →  [[3],[20,9],[15,7]]
[1]                       →  [[1]]
[]                        →  []

Hints

  1. Start from ordinary level-order BFS (process len(queue) nodes per level).
  2. Don't change the order you enqueue children. Just reverse the collected values on odd levels.

Approach

Run standard BFS, collect each level's values, and reverse the list on every odd level (or write values into a deque from the left on those levels).

Don't try to flip the child-enqueue order. That breaks the next level's order in subtle ways. Reversing the output list is O(width) per level, so the total stays O(n).

Complexity

Time: O(n). Space: O(w).

Python solution
def zigzagLevelOrder(root):
    out, level, ltr = [], [root] if root else [], True
    while level:
        vals = [n.val for n in level]
        out.append(vals if ltr else vals[::-1])
        ltr = not ltr
        level = [c for n in level for c in (n.left, n.right) if c]
    return out
JavaScript solution
function zigzagLevelOrder(root) {
  const out = [];
  let level = root ? [root] : [], ltr = true;
  while (level.length) {
    const vals = level.map((n) => n.val);
    out.push(ltr ? vals : vals.reverse());
    ltr = !ltr;
    const next = [];
    for (const n of level) { if (n.left) next.push(n.left); if (n.right) next.push(n.right); }
    level = next;
  }
  return out;
}