I can't find what is wrong with my deletion algorithm. When I run my delete method on the root of the BST, it will replace the root with the value of the minimum of the right subtree, but it is not deleting the node thereafter.
public void delete(BinaryTreeNode node, int x){
if (node==null)
return;
else if (x<node.getKey())
delete(node.getLeftChild(),x);
else if (x>node.getKey())
delete(node.getRightChild(),x);
else{
if (node.getLeftChild()==null)
node = node.getRightChild();
else if (node.getRightChild()==null)
node = node.getLeftChild();
else{
BinaryTreeNode temp = findMin(node.getRightChild());
System.out.println(temp.getKey() + " " + node.getKey());
node.setKey(temp.getKey());
System.out.println(temp.getKey() + " " + node.getKey());
delete(node.getRightChild(), node.getKey());
}
}
}
and my findMin() method:
public BinaryTreeNode findMin(BinaryTreeNode node){
if (node.getLeftChild()==null)
return node;
else
return findMin(node.getLeftChild());
}
For a BST containing all integers 1-9 with a root of 4, my output for inorderPrint() yields
1,2,3,5,5,6,7,8,9
instead of
1,2,3,5,6,7,8,9
findMin(...)
method iteratively instead of recursively. – But I'm Not A Wrapper Class