KatInterview

Alternating Direction Level Order Tree Traversal

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbfsbinary-treelevel-order

Last 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: where values[i] holds the integer value stored in node i
  • children: where children[i] is a two-element list [left_child, right_child] containing the indices of node i's children, or -1 if 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 where n is 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