I am trying to write a method to remove Node from a binary search tree. Here is my method for removing 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 tested this method on the node sheet, although after debugging I found that the execution of nodeToBeSelected=null is running, Node is not actually deleted. Since I can still find the remote value, and the program still manages to retrieve it.
tree.add(5); tree.delete(5); System.out.println(tree.getNode(5).getValue());
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; }
The getNode () method returns the found Node by value? How can I make it return a link and directly manipulate the found node?
source share