KatInterview

Prune All Leaves Matching a Value, Cascading Upward

Trees & GraphsAuto-graded · 18 test cases
HardAuto-gradedTrees & Graphsbinary-treepost-order-traversalrecursion

Last 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 None marking an absent child. Children of absent nodes are never listed.
  • Trailing None values 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 val but 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 1 and 5000 nodes.
  • The tree's height is at most 500.
  • Node values and val are 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.