Delete Leaves With a Given Value

medium tree dfs

Problem

Given a binary tree root and an integer target, delete all leaf nodes with value equal to target. After deleting a leaf, its parent may become a leaf; if so, delete it as well, repeating until no more deletions are possible.

Inputroot = [1,2,3,2,null,2,4], target = 2
Output[1,null,3,null,4]
Leaves with value 2 are deleted; their parent (2) then becomes a leaf and is also pruned.

def remove_leaf_nodes(root, target):
    if not root: return None
    root.left = remove_leaf_nodes(root.left, target)
    root.right = remove_leaf_nodes(root.right, target)
    if not root.left and not root.right and root.val == target:
        return None
    return root
function removeLeafNodes(root, target) {
  if (!root) return null;
  root.left = removeLeafNodes(root.left, target);
  root.right = removeLeafNodes(root.right, target);
  if (!root.left && !root.right && root.val === target) return null;
  return root;
}
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);
        if (root.left == null && root.right == null && root.val == target) return null;
        return root;
    }
}
TreeNode* removeLeafNodes(TreeNode* root, int target) {
    if (!root) return nullptr;
    root->left = removeLeafNodes(root->left, target);
    root->right = removeLeafNodes(root->right, target);
    if (!root->left && !root->right && root->val == target) return nullptr;
    return root;
}
Time: O(n) Space: O(h)