1325. Delete Leaves With a Given Value
Problem
Delete every leaf whose value is target. If that turns a parent into a leaf with value target, delete it too, and keep going until no such leaf remains.
Example: [1,2,3,2,null,2,4], target = 2 → [1,null,3,null,4]
Post-order: clean both subtrees first, then decide about the node — after its children are deleted it may have become a target leaf itself, which cascades upward naturally.
Complexity: O(n).
class Solution:
def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:
if not root:
return None
root.left = self.removeLeafNodes(root.left, target)
root.right = self.removeLeafNodes(root.right, target)
if not root.left and not root.right and root.val == target:
return None
return root
assert tree_vals(Solution().removeLeafNodes(make_tree([1, 2, 3, 2, None, 2, 4]), 2)) == [1, None, 3, None, 4]
assert tree_vals(Solution().removeLeafNodes(make_tree([1, 3, 3, 3, 2]), 3)) == [1, 3, None, None, 2]
assert tree_vals(Solution().removeLeafNodes(make_tree([1, 2, None, 2, None, 2]), 2)) == [1]
assert Solution().removeLeafNodes(make_tree([1, 1, 1]), 1) is None
class Solution {
public TreeNode removeLeafNodes(TreeNode root, int target) {
if (root == null) return null;
root.left = removeLeafNodes(root.left, target);
root.right = removeLeafNodes(root.right, target);
return root.left == null && root.right == null && root.val == target ? null : root;
}
}
func removeLeafNodes(root *TreeNode, target int) *TreeNode {
if root == nil {
return nil
}
root.Left = removeLeafNodes(root.Left, target) // children first: a parent may become a leaf
root.Right = removeLeafNodes(root.Right, target)
if root.Left == nil && root.Right == nil && root.Val == target {
return nil
}
return root
}