我认为此代码中存在一个错误。我构建了两个不同的BST,并在两者上执行了删除方法。一个工作,另一个没工作。
public void delete(int data) {
root = delete(root, data);
}
private Node delete(Node node, int data) {
if(node == null) throw new IllegalStateException("Empty BST. Cannot delete.");
if(data < node.data) {
delete(node.left, data);
}
else if(data > node.data) {
delete(node.right, data);
}
else {
if(node.left == null)
return node.right;
else if(node.right == null)
return node.left;
else {
// getting data from the rightmost node in the left subtree
// because its greater than all the elements the left subtree of the deleted node
// and smaller than all the elements in the right subtree of the deleted node
node.data = retrieveData(node.left);
// delete the rightmost node in the left subtree
node.left = delete(node.left, node.data);
}
}
return node;
}
private int retrieveData(Node node) {
while(node.right != null)
node = node.right;
return node.data;
}
主要
中的代码 BinarySearchTree bst = new BinarySearchTree(5, 2, 12, -4, 3, 9, 21, 19, 25);
System.out.println(bst.levelOrder());
bst.delete(12);
System.out.println(bst.levelOrder());
bst = new BinarySearchTree(4, 2, 6, -1, 8, 7);
System.out.println(bst.levelOrder());
bst.delete(6);
System.out.println(bst.levelOrder());
输出
[5, 2, 12, -4, 3, 9, 21, 19, 25]
[5, 2, 9, -4, 3, 21, 19, 25]
[4, 2, 6, -1, 8, 7]
[4, 2, 6, -1, 8, 7]
节点(12)已被删除,BST维持其结构。 但是,节点(6)尚未删除。