Problem 156
Binary Tree Zigzag Level Order
Medium · 20 pts · Tree, Breadth-First Search, Binary Tree
Problem
You are given a binary tree. Print its values level by level, but alternate the direction: the first level from left to right, the second from right to left, the third from left to right again, and so on. Print one line per level. Do a normal level-order traversal with a queue, collect each level's values from left to right, and reverse every second level before printing it.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).
Output
Print one line per level, space-separated.
Constraints
1 <= number of nodes <= 2000; -100 <= value <= 100
Example input
7 3 9 20 null null 15 7
Example output
3 20 9 15 7
Explanation
Level 1 is 3. Level 2 is 9 20 from left to right, so it is printed reversed as 20 9. Level 3 is 15 7 and is printed left to right. The lines are 3, 20 9 and 15 7.