MEDIUM Trees / BFS

103. Binary Tree Zigzag Level Order Traversal

๐Ÿ“– Problem

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขLevel-order traversal
  • โ€ขQueue discipline
  • โ€ขShortest-step interpretation

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply BFS reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use BFS with queue for level order traversal
  • โ†’ Track direction flag to zigzag between levels
  • โ†’ Reverse alternate levels before adding to result
  • โ†’ Time: O(n), Space: O(w) where w is max width

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse BFS with queue for level order traversal
  • โ€ขTrack direction flag to zigzag between levels
  • โ€ขReverse alternate levels before adding to result

Common Pitfalls

  • โ€ขTime: O(n), Space: O(w) where w is max width

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
zigzagLevelOrder(buildTree([3,9,20,null,null,15,7]));
Expected:
[[3], [20,9], [15,7]]
Test Case 2
Not run
Input:
zigzagLevelOrder(buildTree([1]));
Expected:
[[1]]
Test Case 3
Not run
Input:
zigzagLevelOrder(buildTree([]));
Expected:
[]

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ

๐Ÿ”— Related Problems

โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit