← DiffPush

Zig-Zag / Spiral Level Order Traversal

Standard Bar Binary Trees · Medium Problems O(n) · O(n)

The Snake-Queue Boarding Call

A themed attraction loads guests from a binary-tree map of queue pens. The host calls one pen-depth at a time, but alternates the walking direction each round to keep the line moving past both entrances: first pen-depth left to right, next right to left, and so on. The announcer needs the exact call order grouped by pen-depth for the day's schedule.

Input: The root of a binary tree given as a level-order array where null marks a missing child.

Output: Return a list of lists: level i holds that level's values, left-to-right for even levels (0-indexed) and right-to-left for odd levels.

Constraints

Examples

Example 1

Input: {"tree":[3,9,20,null,null,15,7]}
Output: [[3],[20,9],[15,7]]
Level 1 runs right-to-left, so 20 precedes 9.

Example 2

Input: {"tree":[1]}
Output: [[1]]
A single pen holds a single guest.

Solve this in your browser →

Also on LeetCode ↗