Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Trees

Delete Leaves With a Given Value

MEDIUM✓ CHIP-TIMEDLC #1325 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Strip every leaf carrying a target value — and keep stripping, since removing a leaf can turn its parent into a new leaf that also needs checking against the same target.

A binary tree and a target value arrive, and any leaf whose value matches the target gets removed.

Removing a leaf can turn its parent into a brand-new leaf, and if that parent also matches the target, it gets removed too — the stripping cascades upward along a branch for as long as matches keep appearing.

The result is the tree after every possible cascade has finished, handed back as its root, which can end up null if the cascade eats the whole tree.

  • tree sizes stay in the low thousands of nodes
  • values are ordinary integers, target included
  • a whole branch can vanish if every node on it matches the target
  • the cascade only stops once no remaining leaf matches
EX 01
root = [] · target = 5
→ []
empty tree
EX 02
root = [1] · target = 1
→ []
single node, whole tree removed
EX 03
root = [1] · target = 2
→ [1]
single node, target absent

The hintstake only what you need

HINT 1 THE NUDGE

One sweep that deletes today's leaves isn't the whole answer — a parent can become a leaf only after its own child is gone, and it might match the target too.

HINT 2 THE STRUCTURE

Deletions cascade upward, one generation at a time, only along branches where every descendant also happened to match.

HINT 3 ONE STEP FROM THE ANSWER

Postorder: clean both children first, THEN check if the current node is now childless and equal to target. Doing the check after the recursive calls (not before) makes the cascade happen for free in a single pass.

Coach's boardthe pattern, step by step

THE CASCADE UPPATTERN · POSTORDER PRUNEroot = [1, 2, null, 1, null, 1, null] · target = 1
STEP 1

Postorder: clean both children first, THEN check if this node is now a childless leaf equal to target 1.

STEP 1 / 7 · ← → WORK TOO

The splitstwo paces, two languages

grind/delete-leaves-with-a-given-value.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:
        if not root:
            return None
        root.left = self.removeLeafNodes(root.left, target)
        root.right = self.removeLeafNodes(root.right, target)
        if not root.left and not root.right and root.val == target:
            return None
        return root
TIME O(N)SPACE O(H)PYTHON · RACE PACE · 9 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED