1325. Delete Leaves With a Given Value

T: O(n)

S: O(n)

```java
class Solution {
    public TreeNode removeLeafNodes(TreeNode root, int target) {
        int result = dfs(root, target);
        if (result != 0) {
            return null;
        }
        return root;
    }
    private int dfs(TreeNode node, int target) {
        if (node == null) {
            return 0;
        }
        int leftCount = dfs(node.left, target);
        if (leftCount != 0) {
            node.left = null;
        }
        int rightCount = dfs(node.right, target);
        if (rightCount != 0) {
            node.right = null;
        }
        if (node.left == null && node.right == null) {
            return node.val == target ? 1 : 0;
        }
        return 0;
    }
}
```

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode removeLeafNodes(TreeNode root, int target) {
        return dfs(root, target);
    }
    private TreeNode dfs(TreeNode node, int target) {
        if (node == null) {
            return null;
        }
        node.left = dfs(node.left, target);
        node.right = dfs(node.right, target);
        if (node.left == null && node.right == null && node.val == target) {
            return null;
        }
        return node;
    }
}
```

Last updated