Problem Description
Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once a leaf node is deleted, its parent node may become a leaf with the same target value and should also be deleted. Continue this process until no such leaf nodes remain.
Key Insights
- Use a recursive postorder traversal (process children before the current node).
- After processing the subtrees, check if the current node is a leaf with the target value.
- Removing a leaf might cause its parent to become a new leaf with the target, requiring further deletion.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the tree, as each node is visited once. Space Complexity: O(h), where h is the height of the tree, due to recursion stack usage.
Solution
The solution employs a postorder DFS approach. This ensures that both the left and right subtrees are processed completely before evaluating the parent node. As soon as the helper function processes and updates the left and right children recursively, it checks if the current node has become a leaf that matches the target. If it does, the function returns null to effectively remove the node from the tree. This method naturally handles the cascading deletion of nodes that become eligible as new leaves with the target value.