Binary Tree Zigzag Level Order Traversal - Problem

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values.

In zigzag level order traversal:

  • Level 0 (root): traverse from left to right
  • Level 1: traverse from right to left
  • Level 2: traverse from left to right
  • And so on, alternating direction for each level

The result should be a 2D array where each sub-array contains the values of nodes at that level in the specified order.

Input & Output

Example 1 — Standard Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
💡 Note: Level 0: [3] (left→right), Level 1: [9,20] becomes [20,9] (right→left), Level 2: [15,7] (left→right)
Example 2 — Single Node
$ Input: root = [1]
Output: [[1]]
💡 Note: Only root node exists, so result is [[1]]
Example 3 — Left-Heavy Tree
$ Input: root = [1,2,3,4,null,null,5]
Output: [[1],[3,2],[4,5]]
💡 Note: Level 0: [1], Level 1: [2,3] becomes [3,2], Level 2: [4,5] stays [4,5]

Constraints

  • The number of nodes in the tree is in the range [0, 2000]
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
Binary Tree Zigzag Level Order Traversal INPUT Binary Tree Structure 3 L0 9 20 L1 15 7 L2 L0: Left --> Right L1: Right --> Left L2: Left --> Right root = [3,9,20,null,null,15,7] BFS ALGORITHM 1 Initialize Queue Add root to queue, level=0 queue: [3] | direction: L-->R 2 Process Level Dequeue all nodes at level L0: [3] (L-->R) L1: [9,20] --> [20,9] (R-->L) L2: [15,7] (L-->R) 3 Toggle Direction Alternate: even=L-R, odd=R-L if (level % 2 == 1): reverse(currentLevel) 4 Add Children Enqueue left, then right child Add: node.left, node.right FINAL RESULT Zigzag Traversal Order Level 0: [3] L --> R Level 1: [20,9] R --> L (reversed) Level 2: [15,7] L --> R Output: [[3],[20,9],[15,7]] OK - Zigzag Complete Time: O(n) | Space: O(n) Key Insight: Use standard BFS with a queue, but reverse the order of nodes at odd-numbered levels. The zigzag pattern is achieved by checking (level % 2 == 1) and reversing that level's array. TutorialsPoint - Binary Tree Zigzag Level Order Traversal | BFS Approach
Asked in
Amazon 45 Microsoft 38 Google 32 Facebook 28
78.0K Views
High Frequency
~25 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen