Binary Tree Zigzag Level Order Traversal
medium
binary-tree
breadth-first-search
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values — left to right for level 0, right to left for level 1, then alternating for each subsequent level.
Input / output
- Input:
root: TreeNode(JSON test fixture uses a LeetCode-style level-order array such as[3,9,20,null,null,15,7], withnullfor missing children) - Output:
int[][]
Constraints
- 0 <= number of nodes <= 2000
- -100 <= Node.val <= 100
Follow-up
Can you do this in one BFS pass without calling reverse() on every other level, by placing each value directly into its final index for that level?
Examples
Example 1
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Example 2
Input: root = [1]
Output: [[1]]
Example 3 (empty tree)
Input: root = []
Output: []
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.