Zigzag level order
Challenge · Write code · about 15 min
Given the root of a binary tree, return its values level by level in zigzag order. Level 0 reads left to right, level 1 right to left, level 2 left to right again, and so on.
Example 1
Input:
[[3,9,20,null,null,15,7]]
Output:
[[3],[20,9],[15,7]]
Level 1 is read right to left: [20, 9].
Example 2
Input:
[[1,2,3,4,5,null,6]]
Output:
[[1],[3,2],[4,5,6]]
Constraints
- 0 ≤ number of nodes ≤ 1,000
- -1,000 ≤ Node.val ≤ 1,000
- The tree is given in level order; null marks a missing child
Learn the idea first: Level-order traversal, a visual lesson.
More Level-order traversal problems
- Who leaves the queue next? Warm-up
- Complete the level loop Warm-up
- Level order Standard
- Right side view Standard
- Average of levels Standard