Delete Leaves With a Given Value - Problem
Given a binary tree root and an integer target, delete all the leaf nodes with value target.
Note: Once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted. You need to continue doing this until you cannot delete any more nodes.
Input & Output
Example 1 — Basic Leaf Deletion
$
Input:
root = [1,2,3,2,null,2,4], target = 2
›
Output:
[1,null,3,null,4]
💡 Note:
First remove leaf nodes with value 2, which are at positions. After removal, some nodes become new leaves with value 2, so continue deleting until no target leaves remain.
Example 2 — Cascade Deletion
$
Input:
root = [1,3,3,3,2], target = 3
›
Output:
[1,3,null,null,2]
💡 Note:
Remove leaf node 3, then the parent 3 becomes a leaf and gets removed too. Continue until no more target leaves exist.
Example 3 — Complete Deletion
$
Input:
root = [1,1,1], target = 1
›
Output:
[]
💡 Note:
All leaf nodes are 1, after removing them, root becomes leaf with value 1, so it gets deleted too. Final tree is empty.
Constraints
- 1 ≤ Number of nodes ≤ 3000
- 1 ≤ Node.val ≤ 1000
- 1 ≤ target ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with target value leaf nodes
2
Remove Leaves
Delete leaf nodes matching target value
3
Cascade Effect
New leaves may need deletion too
Key Takeaway
🎯 Key Insight: Use post-order DFS to process children before parents, enabling single-pass cascade deletion
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code