◀ THE GRIND — TREES

Delete Leaves With a Given Value

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.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

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.

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 HINTS — TAKE 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 BOARD — THE 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 SPLITS — TWO PACES, TWO LANGUAGES
grind/delete-leaves-with-a-given-value.pyRACE 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-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED