从二叉搜索树中递归删除
2022-09-03 15:53:52
这是家庭作业;请不要只是给我代码
我有两种方法:和.remove(T data)
removeRec(Node<T> node, T data)
在当前状态下,我的代码似乎只删除了BST的节点。root
@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);
}
我的老师告诉我(作为提示),我应该看看第三个参数传入方法的内容,在这种情况下,.我不明白这有什么帮助,或者如何利用它。我不明白使用第三个参数有什么帮助;我在网上找不到任何关于你为什么要这样做的东西。BSTNode<T> temp