Show problems as
Classic problem #103MediumTreeBreadth-First SearchBinary Tree

Binary Tree Zigzag Level Order Traversal

Real-world version: Relay Tower Snake Sweep
Tracked in this browser only
Read Binary Tree Zigzag Level Order Traversal on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstTraversal · Binary Trees & BST, animated step by step

A broadcast network is wired as a binary tree of relay towers. Every tower carries a signed drift reading, and each tower feeds at most two towers below it.

The network arrives as towers, a flat listing built depth by depth: towers[0] is the tower at the top, and after it come the two feeds of each listed tower, in the order those towers appear. A missing feed is written as null, and nothing is listed underneath a null. Trailing null entries are omitted. An empty listing means the network has no towers at all.

An inspector logs the network one depth at a time, but alternates the direction of travel: the topmost depth is logged from left to right, the depth under it from right to left, the one after that from left to right, and so on down the network.

Return a list whose i-th entry is the list of drift readings at depth i, in the order the inspector logs them. Return an empty list for a network with no towers.

Examples

Example 1

Input
towers = [4, 9, 3, null, null, 6, 8]
Output
[[4], [3, 9], [6, 8]]

Depth 0 holds 4. Depth 1 holds 9 then 3 in wiring order, logged in reverse. The tower holding 9 feeds nothing, so depth 2 is 6 then 8 and is logged forward.

Example 2

Input
towers = [-100, 100, 0, 5, null, null, -7]
Output
[[-100], [0, 100], [5, -7]]

Readings can sit at either end of the allowed range. Depth 1 reverses to 0 then 100, while depth 2 keeps the wiring order 5 then -7.

Example 3

Input
towers = [5, null, 3, null, 2]
Output
[[5], [3], [2]]

Each depth carries a single tower, so reversing a depth changes nothing.

Constraints

  • The number of towers is in the range [0, 2000].
  • -100 <= drift reading <= 100

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def snake_sweep(towers: list) -> list[list[int]]:
Java
public List<List<Integer>> snakeSweep(Integer[] towers)