Question

I have a slightly working binary search tree delete value function. The only time that it does not work is if you are trying to delete a root that has two children.

public boolean delete(BinaryTreeNode node, int i){
    if (node == null){
    return false;
    } else {
        if (node.getKey() == i){
            BinaryTreeNode parent = new BinaryTreeNode(0, null, null);
            parent.setLeftChild(root);
            boolean result = deleteHelper(i, node, parent);
            root = parent.getLeftChild();
            return result;
        } else {
            return deleteHelper(i, node, null);
        }
    }
}

public boolean deleteHelper(int value, BinaryTreeNode curr, BinaryTreeNode parent){
    if (value < curr.getKey()){
        if (curr.getLeftChild() != null){
            return deleteHelper(value, curr.getLeftChild(), curr);
        } else {
            return false;
        }
    } else if (value > curr.getKey()){
        if (curr.getRightChild() != null){
            return deleteHelper(value, curr.getRightChild(), curr);
        } else {
            return false;
        }
    } else {
        if (curr.getRightChild() != null && curr.getLeftChild() != null){
            curr.setKey(findMin(curr.getRightChild()).getKey());
            deleteHelper(curr.getKey(), curr.getRightChild(), curr);
        } else if (parent.getLeftChild() == curr){
            parent.setLeftChild((curr.getLeftChild() != null)?curr.getLeftChild():curr.getRightChild());
        } else if (parent.getRightChild() == curr){
            parent.setRightChild((curr.getLeftChild() != null)?curr.getLeftChild():curr.getRightChild());
        }
        return true;
    }
}
Was it helpful?

Solution

According to Wikipedia

Deleting a node with two children: Call the node to be deleted N. Do not delete N. Instead, choose either its in-order successor node or its in-order predecessor node, R. Copy the value of R to N, then recursively call delete on R until reaching one of the first two cases. http://en.wikipedia.org/wiki/Binary_search_tree#Deletion

You can try by successor node as follows:

  1. get successor of node to delete (current)
  2. connect parent of current to successor
  3. connect successor to the left child for current

For more details check out this link

Java, Binary tree remove method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top