Prune All Leaves Matching a Value, Cascading Upward
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests whether a candidate can use post-order traversal to handle cascading leaf deletions in a binary tree encoded as a level-order list.
You are given a binary tree and an integer val. Your task is to remove every leaf node whose value equals val. When you remove a leaf, its parent may become a leaf; if that newly exposed leaf also has value val, remove it too. Keep repeating until the tree contains no leaf whose value equals val. Return the resulting tree. If every node ends up removed, return an empty list.
Tree Encoding
Both the input and the output use the same level-order (BFS) encoding:
- An empty tree is represented as
[]. - Otherwise the first element is the root's value. Nodes are then visited left-to-right level by level, and for each present node its left child value and then its right child value are appended, with
Nonemarking an absent child. Children of absent nodes are never listed. - Trailing
Nonevalues are omitted from the end of the list.
The input is always a well-formed encoding. Your output must be in exactly this canonical form.
Rules
- A leaf is a node with no children.
- A node whose value equals
valbut that still has at least one child after all deletions are applied is kept in place. - No node ever changes position: every surviving node retains its original parent and its left-or-right side.
- The returned tree must contain no leaf whose value equals
val.
Constraints
- The tree contains between
1and5000nodes. - The tree's height is at most
500. - Node values and
valare integers in the range[-1 000 000 000, 1 000 000 000].
Examples
Example 1
Input: prune_matching_leaves([5, 7, 7, 7, 3, None, 7], 7)
Output: [5, 7, None, None, 3]
Example 2
Input: prune_matching_leaves([3, 3, 1], 3)
Output: [3, None, 1]
Example 3
Input: prune_matching_leaves([4, 4, 4], 4)
Output: []
Hints
Hint 1
Think about when you can decide whether a node should be deleted. You need to know what's left of its children first — which traversal order gives you that?
Hint 2
A node is deleted only when it has no remaining children AND its value equals `val`. Process children before the parent so each decision is made with complete information.
Hint 3
After pruning, re-encode the surviving tree carefully: emit `None` for absent children to preserve positional correctness, enqueue only present children, and strip any trailing `None`s at the very end.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight: post-order traversal
The cascade moves upward: a deletion at a leaf can expose a new leaf one level up, which may need deleting, and so on. The key observation is that a node's fate depends entirely on what survives in its subtrees — information that only exists after the subtrees have been fully processed. That makes post-order traversal the natural fit: recurse into both children first, then decide about the current node.
The decision rule is simple:
- If both child slots are now
None(the node is a leaf) and its value equalsval, returnNoneto the parent, signalling deletion. - Otherwise return the node as-is.
The parent assigns the returned value back into its child slot: node[1] = prune(node[1]). This cleanly handles deletion without needing to track parent pointers, and it handles deletion of the root naturally — prune just returns None and the caller checks for that.
A single bottom-up pass handles the entire cascade. There is no need to loop until nothing changes.
Why it is correct
By induction on subtree height:
- Base case. A leaf has no children. Both recursive calls return
None. The leaf is deleted exactly when its value equalsval— which matches the rule. - Inductive step. By hypothesis, after both recursive calls each child slot holds exactly what survives in that subtree.
- If at least one child survives, the node is not a leaf, so it is kept regardless of its value.
- If neither child survives, the node has become a leaf, and the rule deletes it if and only if its value equals
val.
Two consequences worth noting:
- Order independence. The surviving set is the same no matter what order individual deletions are applied. A node disappears precisely when its entire subtree consists of nodes that all eventually vanish, a property of the subtree alone.
- No position changes. The code only ever replaces a child pointer with
None. Children are never re-linked, so every surviving node keeps its original parent and side.
Encoding and decoding
Decoding uses a BFS queue of created nodes and a cursor pos into the input list. For each dequeued node, the next two list entries are its left and right children. A None entry means the child is absent; absent nodes are never enqueued, so their children are never read — consistent with the encoding rule that children of absent nodes are not listed. If the list runs out, remaining children are treated as absent, which handles omitted trailing Nones.
Encoding does a BFS over the surviving nodes only:
- For each node, append its left and right child values (or
Nonefor absent children) to the output. - Enqueue only present children.
- Strip trailing
Nones for the canonical form.
Using an index pointer (qpos) rather than pop(0) keeps each BFS step O(1) and avoids accidentally making the overall algorithm O(n²).
Edge cases
- Root alone matches
val.[7], val=7→[].prunereturnsNoneand the caller returns[]. - Entire tree matches
val. The cascade propagates all the way to the root, which is then also deleted. - Root matches
valbut has a surviving child. The root is kept because it is not a leaf after pruning. - A chain collapses on one side only. Nodes on the other side are unaffected.
- No node matches
val. The tree is returned re-encoded in canonical form, unchanged structurally. - Value
0. All presence checks useis not Nonerather than truthiness, so a node with value0is never mistaken for an absent child.
Complexity
- Time: O(n). Decoding, pruning, and encoding each visit every node once.
- Space: O(n). The node list, BFS queue, and output each hold at most O(n) entries. The recursion stack is O(h), where h ≤ 500, well within Python's default recursion limit of 1000. If the tree could be path-shaped with h up to 5000, you would either raise the limit with
sys.setrecursionlimitor rewritepruneas an iterative post-order traversal using an explicit stack.
Full solution
from typing import List
def prune_matching_leaves(tree: List[int | None], val: int) -> List[int | None]:
if not tree:
return []
# --- Decode level-order list into linked nodes [value, left, right] ---
root = [tree[0], None, None]
queue = [root]
pos = 1
qpos = 0
while qpos < len(queue):
node = queue[qpos]
qpos += 1
if pos < len(tree):
value = tree[pos]
pos += 1
if value is not None:
node[1] = [value, None, None]
queue.append(node[1])
if pos < len(tree):
value = tree[pos]
pos += 1
if value is not None:
node[2] = [value, None, None]
queue.append(node[2])
# --- Post-order pruning ---
def prune(node):
if node is None:
return None
node[1] = prune(node[1])
node[2] = prune(node[2])
# Delete this node only if it has become a leaf AND matches val.
if node[1] is None and node[2] is None and node[0] == val:
return None
return node
root = prune(root)
if root is None:
return []
# --- Re-encode survivors in canonical level order ---
result = [root[0]]
queue = [root]
qpos = 0
while qpos < len(queue):
node = queue[qpos]
qpos += 1
for child in (node[1], node[2]):
if child is None:
result.append(None)
else:
result.append(child[0])
queue.append(child)
# Strip trailing Nones for canonical form.
while result and result[-1] is None:
result.pop()
return result