I've written a remove function for a binary search tree that uses a while loop to navigate to the specific node to be removed. However, it's never getting there - it just iterates an unknown number of times and then gives me a NullPointerException.
I was wondering if it was an error in my traversal logic, but it's exactly the same as in my add function, which works perfectly.
void remove(Comparable newObject){
if (!isEmpty()){
Node curr = new Node();
curr = root;
boolean isFound = false;
while (!isFound){
if (curr.data.compareTo(newObject) == 0){
if (curr.hasChildren()){
Node replaceNode = new Node();
if (curr.leftChild == null){
replaceNode = curr.rightChild;
while (replaceNode.leftChild != null){
replaceNode = replaceNode.leftChild;
}
} else {
replaceNode = curr.leftChild;
while (replaceNode.rightChild != null) {
replaceNode = replaceNode.rightChild;
}
}
replaceNode.leftChild = curr.leftChild;
replaceNode.rightChild = curr.rightChild;
replaceNode.parent = curr.parent;
curr = replaceNode;
} else {
curr.data = null;
curr.parent = null;
}
listSize--;
isFound = true;
} else if (curr.data.compareTo(newObject) == 1) {
curr = curr.leftChild;
} else {
curr = curr.rightChild;
}
}
}
}
The data set I'm using yields a root with a left child, and then a right child off of that. The node to be removed is the first (left) child. However, the line that's giving the NullPointerException is
if (curr.data.compareTo(newObject) == 0){
and I'm really not sure at all what's causing this. Any and all help is appreciated greatly.