The delete method only works when i delete the root node of a BST and I dont see the reason why.
public boolean delete(int key){
if(!search(key)) return false;
root = helper(root,key);
return true;
}
public BSTNode helper(BSTNode root,int key){
if (root == null) return root;
if(key < root.key){
root.left = helper(root.left,key);
}else if(key > root.key){
root.right = helper(root.right,key);
}else{
if(root.left == null) return root.right;
if(root.right == null) return root.left;
BSTNode maxFinder = root.left;
while(maxFinder.right != null){
maxFinder = maxFinder.right;
}
root.key = maxFinder.key;
root.left = deleteMax(root.left);
}
return root;
}
public BSTNode deleteMax(BSTNode root){
if(root.right == null){
return root.left;
}
root.right = deleteMax(root.right);
return root;
}
I have tried deleting leaf node, but it won’t delete anything other than the root node.
New contributor
Kijoon Jeong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.