KatInterview

Collect Allowed Values Depth by Depth from a Nested-List Tree

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsbinary-treelevel-orderbfs

Last updated

Traverse a binary tree given as nested lists level by level and keep only values from an allowed set, preserving left-to-right order and empty levels.

A binary tree is encoded as nested lists. Each node is a list [value, left, right], where left and right are either None (no child) or another node in the same format. A node may also be written as just [value] or [value, left], in which case the missing entries count as None.

You are also given a list of integers allowed.

Group the tree's nodes by depth (the root is depth 0). For each depth, collect the values of the nodes at that depth that appear in allowed, ordered from left to right. Return the lists for all depths, shallowest first.

Rules:

  • The filter only decides which values are reported. It never stops the traversal. A node whose value is not allowed can still have descendants whose values are allowed, and those must still be reported.
  • Every depth that exists in the tree produces exactly one list in the result. If no node at that depth is allowed, its list is []. Empty levels are not dropped, so result[d] always describes depth d.
  • If the tree is None, return [].
  • Values may repeat. Compare values only for membership in allowed.

Challenge (optional): do the traversal using only stacks (push, pop, emptiness check) and no queue. Explain how you keep each level in left-to-right order.

Constraints

  • The tree has between 0 and about 10^4 nodes.
  • Node values and entries of allowed are integers.
  • allowed may be empty and may contain duplicates.
  • The tree may be heavily skewed, so a purely iterative solution is safest.

Examples

Example 1

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

Output: [[], [2], [4, 6]]

Example 2

Input: collect_allowed_by_depth([1, [2, None, None], [3, None, None]], [1, 3])

Output: [[1], [3]]

Example 3

Input: collect_allowed_by_depth([7, [3, [1, None, None], None], [9, None, [10, None, None]]], [1, 7, 10])

Output: [[7], [], [1, 10]]

Hints

Hint 1

Process one depth at a time. Keep a container with exactly the nodes of the current depth, and build the container for the next depth while you go.

Hint 2

Failing the filter must not prune anything: always enqueue or push the children, and only the decision to record the value depends on membership. Put `allowed` into a set for fast lookups.

Hint 3

With stacks, popping a level reverses it. If you push children left then right, the next level pops right to left, so move it into a second stack once to restore left-to-right order (or track the reversal explicitly).