This is homework; please don't just give me code
I have two methods: remove(T data)
and removeRec(Node<T> node, T data)
.
In its current state, it seems my code only removes the root
node of the BST.
@Override
public T remove(T data) {
if (data == null) {
throw new IllegalArgumentException("Data is null");
}
if (root == null) {
throw new java.util.NoSuchElementException("BST is empty");
} else {
size--;
BSTNode<T> dummy = new BSTNode<T>(null);
return removeRec(root, data, dummy).getData(); //This is probably wrong too
}
}
/**
* Helper method to recursively search for, and remove the BSTNode with
* the given data in it
* @param node is the node we're currently at
* @param data is the data we're looking for
* @param temp I have no idea why
* @return node that was removed
*/
private BSTNode<T> removeRec(BSTNode<T> node, T data, BSTNode<T> temp) {
if (compare(data, node.getData()) < 0) {
temp.setLeft(removeRec(node.getLeft(), data, temp));
} else if (compare(data, node.getData()) > 0) {
temp.setRight(removeRec(node.getRight(), data, temp));
} else if (node.getLeft() != null && node.getRight() != null) {
temp.setData(findMin(node.getRight()).getData());
temp.setRight(removeRec(node.getRight(), data, temp));
} else {
if (node.getLeft() != null) {
temp = node.getLeft();
} else {
temp = node.getRight();
}
}
return temp;
}
private int compare(T a, T b) {
return a.compareTo(b);
}
My instructor has told me (as a hint) that I should see what passing in a third argument into the method, in this case, BSTNode<T> temp
. I don't understand how that helps though, or how to utilize it. I don't see how using a third argument helps; and I can't find anything online as to why you'd do this either.