category-wise-problems

contains category wise problems(data structures, competitive) of popular platforms.

View the Project on GitHub mayankdutta/category-wise-problems

Delete Leaves With a Given Value

class Solution {
    public TreeNode dfs(TreeNode root, int target) {
        if (root == null) {
            return root;
        }

        root.left = dfs(root.left, target);
        root.right = dfs(root.right, target);

        if (root.val == target)
            if (root.left == null && root.right == null)
                return null;

        return root;
    }
    public TreeNode removeLeafNodes(TreeNode root, int target) {
        return dfs(root, target);

    }
}

another implementation

bool dfs(BinaryTreeNode<int> *root, int x) {
    if (root == nullptr) {
        return false;
    }

    bool left = dfs(root->left, x);
    bool right = dfs(root->right, x);

    if (root->data == x) {
        if (!left && !right) {
            root->left = nullptr;
            root->right = nullptr;
            return false;
        }
    }
    return true;
}

BinaryTreeNode<int>* deleteLeafNodes(BinaryTreeNode<int> *root, int x) {
    auto ans = dfs(root, x);
    return root;
}