Binary Tree Zigzag Level Order Traversal - Problem
Binary Tree Zigzag Level Order Traversal
Imagine you're reading a book where each page is formatted in a unique zigzag pattern - the first line reads left to right, the second line reads right to left, and so on. Your task is to traverse a binary tree in a similar zigzag pattern!
Given the
• Level 0: Read from left to right
• Level 1: Read from right to left
• Level 2: Read from left to right
• And so on, alternating directions...
The result should be a 2D array where each sub-array represents one level of the tree, with values arranged according to the zigzag pattern.
Imagine you're reading a book where each page is formatted in a unique zigzag pattern - the first line reads left to right, the second line reads right to left, and so on. Your task is to traverse a binary tree in a similar zigzag pattern!
Given the
root of a binary tree, return the zigzag level order traversal of its nodes' values. This means:• Level 0: Read from left to right
• Level 1: Read from right to left
• Level 2: Read from left to right
• And so on, alternating directions...
The result should be a 2D array where each sub-array represents one level of the tree, with values arranged according to the zigzag pattern.
Input & Output
example_1.py — Standard Binary Tree
$
Input:
root = [3,9,20,null,null,15,7]
›
Output:
[[3],[20,9],[15,7]]
💡 Note:
Level 0: [3] (left to right), Level 1: [9,20] becomes [20,9] (right to left), Level 2: [15,7] (left to right)
example_2.py — Single Node
$
Input:
root = [1]
›
Output:
[[1]]
💡 Note:
Only one node at level 0, so result is simply [[1]]
example_3.py — Empty Tree
$
Input:
root = []
›
Output:
[]
💡 Note:
Empty tree returns empty result array
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Imagine each tree level as a line of text in a special book
2
Level 0
Read the first line normally from left to right: [3]
3
Level 1
Read the second line backwards from right to left: [9,20] → [20,9]
4
Level 2
Read the third line normally from left to right: [15,7]
5
Result
Combine all lines to get [[3], [20,9], [15,7]]
Key Takeaway
🎯 Key Insight: Use BFS to process levels sequentially, then simply reverse alternate levels to achieve the zigzag pattern efficiently in O(n) time.
Time & Space Complexity
Time Complexity
O(n)
Visit each node exactly once in BFS traversal, plus O(n/2) for reversing alternate levels
✓ Linear Growth
Space Complexity
O(w)
Queue stores at most w nodes where w is maximum width of tree, typically O(n/2) for complete binary tree
✓ Linear Space
Constraints
- The number of nodes in the tree is in the range [0, 2000]
- Node values are in range [-100, 100]
- Tree can be unbalanced
- Follow-up: Can you solve this using O(1) extra space?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code