Repeatedly remove leaf nodes whose value matches a target, until no such leaf remains.
You are given the root of a binary tree and an integer target value.
In one operation, delete every leaf node whose value is equal to target. After those leaves are removed, some parent nodes may become new leaves. Continue performing this operation repeatedly until there are no leaf nodes with value target left in the tree.
Return the root of the resulting tree. If the entire tree is removed, return null.
The key challenge is that deletions can expose new leaves, so the pruning may need to happen bottom-up.
Input Format
- A binary tree root
root. - An integer
target.
The tree is typically represented in level-order form when serialized for testing.
Output Format
- Return the root of the tree after repeatedly deleting target-valued leaves.
- If the tree becomes empty, return
null.
Constraints
- The tree may contain any integer values.
- Deletions are applied repeatedly until stable.
- A node is removable only if it is a leaf at the moment of deletion and its value equals
target.
Example 1
Input
root = [1,2,3,2,null,2,4], target = 2
Output
[1,null,3,null,4]
Explanation
First, the leaf nodes with value 2 are removed. That may create new leaves; after pruning stabilizes, the remaining tree keeps only nodes 1, 3, and 4 in the structure shown.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.