Return a Binary Tree in Zigzag Level Order
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Implement `zigzag_level_order(values)` for a binary tree serialized as a zero-based heap array. For an existing node at index `i`, its children are at `2 * i + 1` and `2 * i + 2`. A `null` slot means no node, and an existing node never appears below a missing parent.
Return one list per tree depth. Values on the root level appear left to right, values on the next level appear right to left, and the direction alternates at every following level. An empty serialization returns an empty list.
For `values = [3, 9, 20, null, null, 15, 7]`, return `[[3], [20,9], [15,7]]`.
Target `O(n)` time and `O(w)` working space, where `w` is the maximum number of nodes on one level, excluding the returned lists.
```hint Keep traversal and output direction separate
Use ordinary breadth-first traversal to discover each level. A deque can place that level's values at the front or back according to the current direction.
```
```hint Alternate once per completed level
Change direction only after consuming the exact number of nodes that belonged to the current level.
```
### Discussion Extensions
- How would two stacks implement the same traversal?
- Why can repeatedly inserting at the front of a dynamic array make a seemingly linear solution slower?
Quick Answer: Return a binary tree's values in zigzag level order using breadth-first traversal. Learn to separate traversal order from output direction while keeping O(n) time and O(w) working space.
Implement zigzag_level_order(values) for a binary tree serialized as a zero-based heap array with null slots. Return each depth as a list, alternating left-to-right and right-to-left order beginning with left-to-right at the root.
Constraints
- 0 <= values.length <= 31, and an existing node never appears below a null parent.
- Each existing value is an integer from -1,000,000,000 through 1,000,000,000.
- A null slot represents a missing node and is not returned.
Examples
Input: ([3, 9, 20, None, None, 15, 7],)
Expected Output: [[3], [20, 9], [15, 7]]
Input: ([1, 2, 3, 4, 5, 6, 7],)
Expected Output: [[1], [3, 2], [4, 5, 6, 7]]
Hints
- Use ordinary breadth-first traversal and process exactly the queue size captured at the start of each level.
- Collect one level in traversal order and reverse that level only when its output direction is right to left.