I am trying to write a method to delete a Node from a Binary Search Tree. Here is my method to delete a node.
public void delete(int deletionNodeValue) {
Node<Integer> nodeToBeDeleted = getNode(deletionNodeValue);
if(nodeToBeDeleted == null) return; // No node with such value exists throw an error
if(isLeafNode(nodeToBeDeleted)) {
nodeToBeDeleted = null;
} else if (nodeToBeDeleted.getNumChildren() == 1) {
bypassNode(nodeToBeDeleted);
}else {
replace(nodeToBeDeleted, getSuccessor(nodeToBeDeleted.getValue()));
}
}
I checked this method on a leaf node, though after debugging I discovered that the execution of nodeToBeSelected=null
takes place, the node isn't actually deleted. As I can still search for the deleted value and program still manages to fetch it.
tree.add(5);
tree.delete(5);
System.out.println(tree.getNode(5).getValue()); // Output : 5, should've been deleted
Here is my getNode() method
public Node<Integer> getNode(int searchValue) {
Node<Integer> currentNode = root;
while(currentNode != null) {
int currentNodeValue = currentNode.getValue();
if(searchValue == currentNodeValue)
return currentNode;
else if(searchValue < currentNodeValue)
currentNode = currentNode.getLeftChild();
else
currentNode = currentNode.getRightChild();
}
// if no node with given value is found
return null;
}
Is getNode() method returning the found node by value? How can I make it return reference and directly manipulate the found node?