SDE & MLE Prep

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