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;
    }
}
```

Last updated

Was this helpful?