Skip to content
Problem 1325 · LeetCode 1325(opens in a new tab)

Delete Leaves With a Given Value

MediumDepth-first search

You are given the root of a binary tree and a number target. Remove every leaf whose value is target.

Removing a leaf can leave its parent with no children. If that parent also holds target, it is now a removable leaf as well. Keep going until no leaf holds target, then return the root of what is left, which may be an empty tree.

Example 1

Input:  root = [1, 4, 4, 4, null, 3, 4], target = 4
Output: [1, null, 4, 3]
Why:    the two 4 leaves go, then the left 4 is a leaf and goes
2 more examples and the constraints

Example 2

Input:  root = [6, 6, 6], target = 6
Output: []
Why:    both children go, then the root is a 6 leaf

Example 3

Input:  root = [5, 2, 8], target = 7
Output: [5, 2, 8]
Why:    no node holds 7

Constraints

  • The tree has between 1 and 3,000 nodes
  • 1 ≤ node value, target ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Strip leaves pass by passO(n·h)
  2. One post-order DFSO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 3,000-node chainVerdict
Strip leaves pass by passO(n·h)
Correct, but repeats the walk
One post-order DFSO(n)
Best; one walk

n = number of nodes, h = tree height.

Edge cases to test

  • Everything goes. [6, 6, 6] with target 6 leaves an empty tree, so return null.
  • Target nowhere. The tree comes back unchanged.
  • Target inside, not at a leaf. In [4, 1] with target 4, the root keeps its child, so it stays.
  • A long chain of targets. Removals ripple all the way up; the recursion is as deep as the chain.

Common mistakes

  • Checking whether a node is a leaf before recursing, which misses parents that become leaves.
  • Removing the child but not writing the result back into node.left or node.right.
  • Returning the original root when the root itself was removed.

How to talk through it

  1. 1Clarify. Can the whole tree disappear? Should a removal ripple up to the parent?
  2. 2Give the simple version. Cut target leaves and repeat until nothing changes; say why it can take n passes.
  3. 3Spot the order. A node becomes a leaf only after its children go, so children first: post-order.
  4. 4Code it. Assign the recursive results to the child links, then test the node.
  5. 5Test out loud. Run a tree that vanishes, one with no target, and a target with a child.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?