Skip to content
Advertisement

Delete leaf nodes between a range in BST

I want to delete the leaf nodes, the values of which are outside a given range (say [L R]). I made a solution in which I was simply traversing all the nodes and checking if my current leaf node’s value is in the given range or not. If it is not then I’m removing this node.

My approach –

private static Node trim(Node root, int L, int R) {
    if (root == null)
        return null;

    if (root.left == null && root.right == null) {
        if (root.val < L || root.val > R)
            return null;
        else
            return root;
    }

    root.left = trim(root.left, L, R);
    root.right = trim(root.right, L, R);

    return root;
}

But this runs in o(n) since I’m traversing all the nodes (and I’m not using BST’s property anywhere). Can anyone help me in finding a better/ optimized solution ?

Advertisement

Answer

Like m.raynal said, since you only want to remove leafs you can’t get better than O(n).

You only can add a shortcut when all the nodes in the branch will be inside the range, something like

private static Node trim(Node root, int L, int R) {

    return trim(root, L, R, null,null);
}

private static Node trim(Node root, int L, int R, Integer lBound, Integer rBound)
{
    if (root == null)
        return null;

    if (lBound != null && lBound >= L && rBound != null && rBound <= R ) {
        return root;
    }
    
    if (root.left == null && root.right == null) {
        if (root.val < L || root.val > R)
            return null;
        else
            return root;
    }

    root.left = trim(root.left, L, R, lBound , root.val);
    root.right = trim(root.right, L, R, root.val, rBound );

    return root;
}
Advertisement