Collect Allowed Values Depth by Depth from a Nested-List Tree
Trees & GraphsAuto-graded · 18 test casesLast 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, soresult[d]always describes depthd. - 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
allowedare integers. allowedmay 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).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk the tree one depth at a time. Keep a stack current holding exactly the nodes of the present depth, arranged so that popping returns them from left to right. Pop every node in current:
- If its value is in the allowed set, append it to this level's list.
- Push its left child and then its right child onto a second stack,
pushed.
After the level is finished, pushed holds the next depth's nodes, but the rightmost is on top, which is the wrong way round. Pop everything from pushed into a fresh stack. That reverses the order once more, so the leftmost node is on top, and this new stack becomes current for the next depth.
Append the level's list to the result after every depth, even if it is empty.
Why it is correct
Invariant: at the start of each depth, current contains exactly the nodes of that depth and pops them left to right.
- Initially
current = [root], which satisfies the invariant. - If the nodes of depth
dare popped in orderv1, ..., vk(left to right), then the children ofv1come before the children ofv2, and so on, with each left child before its sibling. So the push order ontopushedis the left-to-right order of depthd+1. A stack pops in reverse, so transferring it into a new stack gives a stack that pops left to right again. - Values are recorded in pop order, so each level list is left to right.
- The filter never affects which children are pushed, so allowed descendants of disallowed nodes are not lost.
- Every depth that exists produces one list, so empty levels are kept naturally.
Complexity
- Time: O(n + m), where n is the number of nodes and m is the length of
allowed(to build the set). Each node is pushed and popped at most twice. - Space: O(w) auxiliary, where w is the maximum width of the tree, plus the output. The solution is iterative, so deep trees do not overflow the call stack.
Reference solution
from typing import List, Optional
def collect_allowed_by_depth(tree: Optional[list], allowed: List[int]) -> List[List[int]]:
if tree is None:
return []
allowed_set = set(allowed)
result: List[List[int]] = []
# Stack invariant: popping yields the nodes of the current depth left to right.
current = [tree]
while current:
level: List[int] = []
pushed = []
while current:
node = current.pop()
if node[0] in allowed_set:
level.append(node[0])
left = node[1] if len(node) > 1 else None
right = node[2] if len(node) > 2 else None
if left is not None:
pushed.append(left)
if right is not None:
pushed.append(right)
result.append(level)
# `pushed` pops right to left; pour it into a fresh stack to reverse it.
reordered = []
while pushed:
reordered.append(pushed.pop())
current = reordered
return result