Alternating Direction Level Order Tree Traversal
Trees & GraphsAuto-graded · 22 test casesLast updated
Tests BFS traversal with directional output reversal per level without corrupting the queue structure.
Given a binary tree represented as parallel arrays, produce its values grouped by depth, where each depth alternates between left-to-right and right-to-left ordering.
You are given two arrays of equal length:
values: wherevalues[i]holds the integer value stored in nodeichildren: wherechildren[i]is a two-element list[left_child, right_child]containing the indices of nodei's children, or-1if a child is absent
When the tree is non-empty, node 0 is always the root. Return a list of lists where each inner list contains all values at a particular depth. The first depth (root level) should be ordered left-to-right, the second depth right-to-left, the third left-to-right, and so on.
Constraints
0 <= len(values) == len(children) <= 200000-1000000000 <= values[i] <= 1000000000- Values may be duplicated
- The input represents a valid binary tree: all nodes are reachable from node
0, there are no cycles, and every non-root node has exactly one parent - Missing children (represented as
-1) should not appear in the output - Return an empty list
[]when the tree is empty - Your solution should run in
O(n)time wherenis the number of nodes
Examples
Example 1
Input: alternating_level_order([10, 20, 30, 40, 50], [[1, 2], [3, 4], [-1, -1], [-1, -1], [-1, -1]])
Output: [[10], [30, 20], [40, 50]]
Example 2
Input: alternating_level_order([7], [[-1, -1]])
Output: [[7]]
Hints
Hint 1
Use breadth-first search to identify which nodes belong to each depth level
Hint 2
Process one complete level at a time by capturing the queue size before dequeuing
Hint 3
Apply direction reversal only to the collected values after a level is complete, never alter the traversal order itself
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to separate two independent concerns: determining which nodes belong to each depth level, and deciding how to present those values in the output.
Use standard breadth-first search to traverse the tree level by level. At each depth, capture the current queue size to know exactly how many nodes belong to that level. Process precisely that many nodes by dequeuing them, recording their values, and enqueuing their children (left before right, skipping -1 markers). This ensures the queue contains only the next level's nodes after each batch completes.
Once all values for a depth are collected into a temporary list, check whether that depth requires reversal. The root is depth 0 (left-to-right), depth 1 goes right-to-left, depth 2 goes left-to-right again, and so forth. Toggle a boolean flag after each level to track this. When reversal is needed, simply call reverse() on the completed list before appending it to the result.
This approach keeps traversal logic unchanged regardless of output direction. Reversing a finished list of values cannot affect the queue contents, so the next level's traversal remains correct.
Why It Works
At the beginning of each iteration, the queue holds exactly the nodes at the current depth, ordered left-to-right. This invariant holds by induction: we seed the queue with the root, then during each level we dequeue all current nodes and enqueue their children in left-then-right order. Because we dequeue exactly as many nodes as were present at the loop start (captured by range(len(queue))), newly enqueued children wait until the next iteration.
Each depth produces one inner list. Reversing that list when the depth index is odd gives the required alternating pattern, while the queue structure ensures correctness for subsequent levels.
Complexity
Time: O(n) where n is the number of nodes. Each node is enqueued once and dequeued once. Checking and enqueuing children takes constant time per node. Reversing a level costs time proportional to that level's size, and all level sizes sum to n, so total reversal cost is O(n). Output construction is also O(n).
Space: O(n) for the output, which contains all n values. The queue holds at most one complete level plus part of the next, which in the worst case (a complete binary tree with roughly n/2 leaves) is O(n). The iterative approach avoids recursion stack depth issues, which matters for input sizes up to 200,000.
Solution Code
from collections import deque
from typing import List
def alternating_level_order(values: List[int], children: List[List[int]]) -> List[List[int]]:
n = len(values)
if n == 0:
return []
result = []
queue = deque([0])
left_to_right = True
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(values[node])
left, right = children[node]
if left != -1:
queue.append(left)
if right != -1:
queue.append(right)
if not left_to_right:
level.reverse()
result.append(level)
left_to_right = not left_to_right
return result