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
Understanding the Visualization
1
Input Tree
Binary tree with nodes at multiple levels
2
Level-by-Level
Process each level with alternating directions
3
Zigzag Result
2D array with zigzag pattern: L→R, R→L, L→R...
Key Takeaway
🎯 Key Insight: Use BFS with direction tracking to build zigzag pattern in a single pass
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code