我正在try 创建一个移除方法,从AVL树中移除一个 node .但是测试我的代码的程序给了我一个错误,说我没有正确使用NoSuchElementException.
下面是我的Remove方法(和emoveRecursive方法)的代码.
public T remove(T data) {
// Base case: if data is null, throw an exception
if (data == null) {
throw new IllegalArgumentException("Error: data cannot be null.");
}
// Recursive helper method for removing data from the tree
AVLNode<T> removedNode = removeRecursive(root, data);
// If the node is not found, throw NoSuchElementException
if (removedNode == null) {
throw new NoSuchElementException("Error: data not found in the tree.");
}
// Update the root after removal
root = removedNode;
return removedNode.getData();
}
private AVLNode<T> removeRecursive(AVLNode<T> current, T data) {
if (current == null) {
return null; // Data not found
}
// Compare data with the current node's data
int compareResult = data.compareTo(current.getData());
if (compareResult < 0) {
// Data is smaller, go to the left subtree
current.setLeft(removeRecursive(current.getLeft(), data));
} else if (compareResult > 0) {
// Data is larger, go to the right subtree
current.setRight(removeRecursive(current.getRight(), data));
} else {
// Node with data found, perform removal based on cases
if (current.getLeft() == null && current.getRight() == null) {
// Case 1: Node is a leaf (no children)
size--;
return null;
} else if (current.getLeft() != null && current.getRight() != null) {
// Case 3: Node has two children
// Replace the data with the successor's data
AVLNode<T> successor = findSuccessor(current.getRight());
current.setData(successor.getData());
// Remove the successor node
current.setRight(removeRecursive(current.getRight(), successor.getData()));
} else {
// Case 2: Node has one child
size--;
return (current.getLeft() != null) ? current.getLeft() : current.getRight();
}
}
// Update height and balance factor, then balance the tree
return balance(current);
}
这就是它给我的错误:
[测试失败:删除]:try 删除树以外的数据时未引发NoSuchElementException.
我很困惑,因为我在判断RemvedNode是否为空时抛出了NoSuchElementException.那么,为什么它说它没有被扔出go 呢?谢谢.
不知道还能试什么.另外,我已经试过调试这个程序,但它仍然显示相同的内容.