public void removeNode(int data) {
deleteNode(root, data);
}
public Node deleteNode(Node focus, int data) {
if(focus == null) {
System.out.println("Tree empty");
return null;
}
else if(data < focus.data) {
deleteNode(focus.leftchild, data);
}
else if(data > focus.data) {
deleteNode(focus.rightchild, data);
}
else {
// No child
if(focus.leftchild == null && focus.rightchild == null) {
focus = null;
}
// one child
else if(focus.leftchild == null) {
focus = focus.rightchild;
System.out.println("here");
}
else if(focus.rightchild == null) {
focus = focus.leftchild;
}
// 2 children
else {
Node temp = findMin(focus.rightchild);
focus.data = temp.data;
deleteNode(focus.rightchild, temp.data);
}
}
return focus;
}
public Node findMin(Node focus) {
while(focus.leftchild != null) {
focus = focus.leftchild;
}
return focus;
}
我已经编写了上面的代码来删除二进制搜索树中的节点。但是由于某种原因,当我运行preordertraversal函数来打印所有节点时,我看到该节点没有被删除。有人可以告诉我为什么节点没有被删除。功能似乎是正确的。
答案 0 :(得分:0)
public Node deleteNode(Node focus, int data) {
if(focus == null) {
System.out.println("Tree empty");
return null;
}
else if(data < focus.data) {
focus.leftchild = deleteNode(focus.leftchild, data);
}
else if(data > focus.data) {
focus.rightchild = deleteNode(focus.rightchild, data);
}
else {
// No child
if(focus.leftchild == null && focus.rightchild == null) {
focus = null;
}
// one child
else if(focus.leftchild == null) {
focus = focus.rightchild;
System.out.println("here");
}
else if(focus.rightchild == null) {
focus = focus.leftchild;
}
// 2 children
else {
Node temp = findMin(focus.rightchild);
focus.data = temp.data;
focus.rightchild = deleteNode(focus.rightchild, temp.data);
}
}
return focus;
}