Given a binary tree root and an integer target, delete all the leaf nodes with value target.
Note that 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 that until you cannot).
Example 1:

Input: root = [1,2,3,2,null,2,4], target = 2 Output: [1,null,3,null,4] Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).
Example 2:

Input: root = [1,3,3,3,2], target = 3 Output: [1,3,null,null,2]
Example 3:

Input: root = [1,2,null,2,null,2], target = 2 Output: [1] Explanation: Leaf nodes in green with value (target = 2) are removed at each step.
Constraints:
[1, 3000].1 <= Node.val, target <= 1000This approach involves using a recursive DFS to navigate through the binary tree. We start from the root and check the leaf nodes. If a leaf node matches the target value, we remove it by returning null; otherwise, return the node itself. This should also be applied recursively to handle cases where removing a leaf creates another leaf node which must also be removed.
In this solution, we recursively dive into the left and right subtrees to remove the leaf nodes with the target value. After modifying both subtrees, we check if the current node has become a leaf with the target value and delete it if so.
Java
C++
Time Complexity: O(n), where n is the number of nodes in the tree, since we visit each node exactly once.
Space Complexity: O(h), where h is the height of the tree, due to the recursion stack.
This approach uses an iterative post-order traversal to visit the nodes of the binary tree. By using a stack, we can simulate the recursive process, ensuring we evaluate and remove leaf nodes correctly by visiting left, right, and then parent nodes.
This JavaScript solution uses an iterative approach to simulate the post-order traversal. By attaching a dummy node to facilitate handling the root node, each node and its corresponding direction (left/right) are pushed onto a stack. As nodes are processed, if a node matches the target and is a leaf, it is removed by setting its parent's pointer to null.
C#
Time Complexity: O(n), each node is visited once.
Space Complexity: O(h), where h is the height of the tree, required for the stack.
| Approach | Complexity |
|---|---|
| Recursive Depth-First Search (DFS) | Time Complexity: O(n), where n is the number of nodes in the tree, since we visit each node exactly once. |
| Iterative Post-Order Traversal | Time Complexity: O(n), each node is visited once. |
Delete Leaves With a Given Value - Leetcode 1325 - Python • NeetCodeIO • 7,635 views views
Watch 9 more video solutions →Practice Delete Leaves With a Given Value with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor