Can't remove root node in Binary Search Tree

Viewed 92

I'm trying to remove the root of my binary search tree so I can update it's value, but this method can't do it. My idea is to remove the root, and then insert it again in the binary search tree but with another value. It works with every Node in the tree, but not the root cause I cannot delete it. Anyone knows why this happens? Thanks.

public V remove(K key) {
    Node node = remove(key, root);
    return node.value;
}

private Node remove(K key, Node current) {
    if (current == null) { 
        return null;
    }
    if (current.key.equals(key)) { 
        
        if (current.left == null && current.right == null) {
            return null;
        } 
        else if (current.left == null && current.right != null) {
            return current.right;
        } else if (current.left != null && current.right == null) {
            return current.left;
        } else {
            Node plowest = current.right;
            Node parent = current;
            while (plowest.left != null) {
                parent = plowest;
                plowest = plowest.left;
            }
            plowest.left = current.left;
            if (plowest != current.right) {
                parent.left = plowest.right;
                plowest.right = current.right;
            }
            return plowest;
        }
    }
    if (key.compareTo(current.key) < 0) { // Subarbre esquerra
        current.left = remove(key, current.left);                                   
    } else {// Subarbre dret
        current.right = remove(key, current.right);
    }
    return current;
}

And this is the main code where I call the method to delete any Node, in this case I would like to delete the root.

public static void main(String[] args) {

    BSTMapping<String, Integer> arbre = new BSTMapping();
    arbre.put("G", 4);
    arbre.put("A", 1);
    arbre.put("C", 2);

    arbre.remove("G");

    Iterator it = arbre.iterator();
    while (it.hasNext()) {
        BSTMapping.Pair p = (BSTMapping.Pair) it.next();
        System.out.println(p.getKey() + " - " + p.getValue());
    }

     
}
1 Answers

When removing root, remove(K key, Node current) never reaches the bottom where it would assign a node to current.left or current.right. You can address this in remove(key) by assigning directly to the root variable when appropriate.

public V remove(K key) {
    Node node = remove(key, root);
    if (root.key.equals(key)) {
       root=node;
    }
    return node.value;
}
Related