我的代码如下。我在删除方法方面遇到问题,我无法删除二进制搜索树中的节点并替换它而不创建两个替换节点...我该如何解决这个问题?
public class BSTMain {
public static void DeleteValue(int num, BSTNode root){
BSTNode cursor = root;
while(true){ //move cursor
while(cursor.getLeft()!=null && num<cursor.getData()){
//move cursor
cursor = cursor.getLeft();
}
while(cursor.getRight()!=null && num>cursor.getData()){
//move cursor
cursor = cursor.getRight();
}
if(cursor.getData() == num || (cursor.getLeft()==null && num<cursor.getData()) || (cursor.getRight()==null && num>cursor.getData())) //check for placing cases
break; //time to delete node in the tree
}
if(cursor.getData()==num){//delete node
if(cursor.getLeft()!=null){ //if left exists
BSTNode cursor2 = cursor.getLeft();
while(cursor2.getRight()!=null){ //get rightmost of left to replace
cursor2 = cursor2.getRight();
}
cursor.setData(cursor2.getData()); //replace cursor
if(cursor2.getLeft()!=null)
cursor2.getLeft().root = cursor2.root; //Replace cursor2
cursor2.root.setRight(cursor2.getLeft());
} else if(cursor.getRight()!=null){ //if no left but right
BSTNode cursor2 = cursor.getRight();
while(cursor2.getLeft()!=null){ //get leftmost of right
cursor2 = cursor2.getLeft();
}
cursor.setData(cursor2.getData()); //replace cursor
if(cursor2.getRight()!=null)
cursor2.getRight().root = cursor2.root; //Replace cursor2
cursor2.root.setLeft(cursor2.getRight());
} else {
System.out.println("Node " + num + " does not exist!");
}
}
else System.out.println(num + " does not exist in Binary Search Tree!");
}
}
一些输出:
按顺序:19 20 21 22 23 23 45
指挥:D 19
删除后:20 20 21 22 23 23 45
命令:D 20
删除后:20 20 21 22 23 23 45
命令:D 21
删除后:20 20 22 23 23 45
命令:D 22
删除后:20 20 20 20 23 23 45
命令:D 23
删除后:20 20 20 20 23 23 20 20 20 20 45
命令:D 45
删除后:20 20 20 23 23 20 20 20 20
命令:D 20
删除后:20 20 20 23 23 20 20 20
命令:D 20
删除后:20 20 20 23 23 20 20
命令:D 20
删除后:20 20 20 23 23 20
命令:D 20
删除后:20 20 20 23 23 23 20 20 20 23
命令:D 23
删除后:20 20 20 23 23 23 20 20 20 23
命令:E