So in my binary search tree, I'm trying to test my delete method to see if it removes a node from the BST. The problem is my test keeps saying that it didn't work. Here's how I'm testing my delete method
message = "Test 3: deleting 'word' -- ";
t = new BSTRefBased();
try {
t.delete("word");
result = t.getRootItem().getWord().equals(null);
} catch (Exception e) {
result = false;
}
System.out.println(message + (result ? "passed" : "failed"));
Here's my delete method:
public void delete(String word) {
root = deleteItem(root, word);
}
protected TreeNode deleteItem(TreeNode r, String word) {
if (r == null){
return r;
}
if(word.compareTo(r.item.getWord()) < 0){
return r;
} else if (word.compareTo(r.item.getWord()) > 0) {
return r;
} else if(r.left != null && r.right != null)
{
return deleteItem(r, word);
} else {
return r;
}
return r;
}
So why does it keep saying that my delete method failed in my output? Is the problem with my test code or with the actual method? Also I did previously insert the word 'word' in my BST so it should be there. Here's a pseudo code version of what I want my delete method to do:
delete(treeNode ,searchitem)
targetNode = search(treeNode ,searchItem)
if targetNode is null
return
P = parent node of target Node
if targetNode has no children
update ref in P that leads to targetNode
return
if targetNode has only one child C update ref in P that leads
to targetNode by overwriting that ref with C
(either left- or right-ref in P)
return
M = targetNode's inorder successor (i.e., left-most in-order
successor in targetNode's right subtree)
m = item in M
copy m into targetNode's item field
delete (treeNode, M)
return