KatInterview

Group Serialized Tree Values by Depth

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstreesbfsarrays

Last updated

Parse a LeetCode-style level-order array and return values grouped into nested lists by depth, preserving left-to-right order.

Problem

You are given a binary tree serialized as a level-order array. The first element is the root. Each non-null element, in order, claims the next two array positions as its left and right children. Null entries have no children and consume no slots. Trailing nulls may be omitted, so the array can end mid-level.

Return the tree's values grouped by depth: the first sublist holds depth-0 values, the second holds depth-1 values, and so on. Within each sublist, preserve left-to-right order.

Implement group_by_depth(serialized).

Constraints

  • The array contains at most 100,000 elements.
  • Elements are signed 32-bit integers or None.
  • Return an empty list for an empty tree or a tree whose root is None.
  • Value 0 is a valid node value and must not be dropped.

Clarifying Questions

  • Is a flat breadth-first list sufficient? No, group by depth.
  • Must left-to-right order be preserved within each level? Yes.
  • Can the tree be a single long chain (skewed)? Yes.
  • Are child references shared or cyclic? No, it is a valid tree.

Examples

Example 1

Input: group_by_depth([3, 9, 20, None, None, 15, 7])

Output: [[3], [9, 20], [15, 7]]

Example 2

Input: group_by_depth([1])

Output: [[1]]

Example 3

Input: group_by_depth([1, 2, 3, None, 4, None, 5])

Output: [[1], [2, 3], [4, 5]]

Example 4

Input: group_by_depth([None])

Output: []

Hints

Hint 1

Recognize the input is a breadth-first serialization, not a node object.

Hint 2

Freeze the current level's size before reading its children.

Hint 3

Use `is not None` checks so value 0 survives.

Hint 4

Advance a single cursor forward through the array; never rescan or pop from the front.