I have this piece of code down below for removing a node from a BST:
private TreeNode<T> remove(T data, TreeNode<T> current) {
if(current == null) {
throw new InputMismatchException("The data element trying to be removed couldn't be found.");
}
else if(data.compareTo(current.data) < 0) {
current.left = remove(data, current.left);
}
else if(data.compareTo(current.data) > 0) {
current.right = remove(data, current.right);
}
else {
if(current.right != null && current.left == null) {
return null;
}
else if(current.right == null && current.left != null) {
if(current.right != null) {
return current.right;
}
return current.left;
}
else {
current.right = findSuccessor(current.right, current);
}
}
size--;
return current;
}
it keeps on giving odd results and I can’t figure out why. Can someone please help?
>Solution :
In your else statement when asserting current.right, you should be checking if it is null rather than if it isn’t.
if(current.right == null && current.left == null) {
return null;
}