Binary Tree Zigzag Level Order Traversal

Medium

Topics
TreeBFS

Given the root of a binary tree, list its values level by level, alternating direction: the root level is read left to right, the next level right to left, the one after that left to right again, and so on. Return a list of levels, each a list of values. On this judge the levels are printed separated by |, and an empty tree prints an empty line.

Example 1

4251637
levels read right to left
Direction alternates per level, so the shaded levels are emitted right to left. The traversal itself stays a normal level-order walk — only the output order of each level flips, so reversing alternate rows is enough and no backwards traversal is needed.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,2,3,4,5,6,7]
Output: [[1],[3,2],[4,5,6,7]]

Example 2

984
levels read right to left
Input:  root = [9,null,4,8]
Output: [[9],[4],[8]]

Example 3

empty tree
Input:  root = []
Output: []

Constraints

  • 0 <= number of nodes <= 2000
  • -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

The set of nodes on each level is exactly what a normal breadth-first traversal produces; only the order inside every other level changes. So run a plain level-order BFS and flip the odd-numbered levels before recording them.

Approach

  1. If the root is empty, return an empty list.
  2. BFS one level at a time: snapshot the queue length, pop that many nodes, collect their values and enqueue their children left then right.
  3. If the level index is odd, reverse the collected values (or fill them into a deque from the front).
  4. Append the level and continue.

Dry Run

tree 1 2 3 4 5 6 7
  level in queue order [1]           reverse=false   record [1]
  level in queue order [2, 3]        reverse=true    record [3, 2]
  level in queue order [4, 5, 6, 7]  reverse=false   record [4, 5, 6, 7]
answer [1] | [3, 2] | [4, 5, 6, 7]
The queue is always built left to right. Only the RECORDED order alternates, and
that separation is the whole point: children are enqueued in a fixed order so the
next level's left-to-right sequence is always correct, and the reversal is applied
to the output list afterwards.
Flipping the enqueue order instead looks equivalent and is not. It gives
[[1], [3, 2], [5, 4, 7, 6]] -- level 2 is right, level 3 is wrong, because
reversing the parents' traversal order permutes their children in pairs rather
than reversing the level. The error compounds with depth, which is why it tends to
pass a two-level test and fail a three-level one.
`reverse` is flipped once per level, unconditionally. Guard the flip with
`if reverse:` and the flag can never leave false in the first place, so nothing
is ever reversed: the output becomes plain level order, [[1], [2, 3],
[4, 5, 6, 7]].

Complexity

  • Time — O(n): every node is enqueued and dequeued once; reversing a level is linear in its size.
  • Space — O(n): the queue can hold a whole level.

Common Pitfalls

  • Changing the order you enqueue children instead of the order you record values scrambles deeper levels.
  • Alternating by a boolean that you forget to flip on every level, including levels you reverse.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def zigzagLevelOrder(self, root):
        if not root:
            return []
        out = []
        level = [root]
        reverse = False
        while level:
            values = [node.val for node in level]
            out.append(values[::-1] if reverse else values)
            nxt = []
            for node in level:
                if node.left:
                    nxt.append(node.left)
                if node.right:
                    nxt.append(node.right)
            level = nxt
            reverse = not reverse
        return out
Asked at Citadel Nutanix
SensAI
Beta
Tap the mic to stop voice mode