Skip to problem
←

Binary Tree Zigzag Level Order Traversal

Medium 0 attempts

You're given the root of a binary tree. Return its node values grouped level by level, but alternate the reading direction of each level — left-to-right, then right-to-left, and so on down the tree.

Function contract

Implement zigzagLevelOrder(root). The runner converts the level-order input array into nodes with val, left, and right fields; [] becomes null.

Output: An array of levels, alternating left-to-right and right-to-left order, starting left-to-right at the root. Return [] for an empty tree.

Example 1

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

Example 2

Input
root = []
Output
[]
Visual Aid
Alternate the reading direction
3920157Level 0 → [3]Level 1 ← [20, 9]Level 2 → [15, 7]

Visit levels from top to bottom. Reverse the reading order on every second level.

Constraints
  • 0 <= number of nodes <= 2000
  • -100 <= Node.val <= 100

BFS with Direction Flag

javascript
function zigzagLevelOrder(root) {
  if (!root) return [];
  const result = [], q = [root];
  let leftToRight = true;
  let head = 0;
  while (head < q.length) {
    const level = [], size = q.length - head;
    for (let i = 0; i < size; i++) {
      const node = q[head++];
      level.push(node.val);
      if (node.left) q.push(node.left);
      if (node.right) q.push(node.right);
    }
    result.push(leftToRight ? level : level.reverse());
    leftToRight = !leftToRight;
  }
  return result;
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript