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
Delete Leaves With a Given Value INPUT Binary Tree (target = 2) 1 2 3 2 2 4 = Target (2) = Keep root = [1,2,3,2,null,2,4] target = 2 Delete all leaves with value 2 ALGORITHM STEPS Post-order DFS (Optimal) 1 Post-order Traverse Process children before parent 2 Recurse Left/Right Update child references 3 Check Leaf Condition Is leaf AND value == target? 4 Delete or Keep Return null or node Deletion Order: 1 2 3 2 1st 2 3rd 4 2nd FINAL RESULT Pruned Tree 1 3 4 X node 2 deleted X Output: [1,null,3,null,4] OK - All target leaves removed Key Insight: Post-order traversal (left-right-root) ensures we process children BEFORE parents. This naturally handles cascading deletions: when a child is deleted, the parent may become a new leaf with target value, and it gets checked immediately. Time: O(n), Space: O(h). TutorialsPoint - Delete Leaves With a Given Value | Post-order DFS (Optimal)
Asked in
Amazon 15 Facebook 12 Microsoft 8
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen