0
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函數來打印所有節點時,我發現該節點沒有被刪除。有人可以告訴我爲什麼一個節點沒有被刪除。該功能似乎是正確的。二叉樹刪除節點功能不起作用
設置'focus = null'或'focus = focus.rightchild'不會刪除節點'focus'。您只需將變量'focus'(只存在於此函數中)指向另一個節點(或'null')。相反,您必須將Node ** ** parent **中的變量設置爲不同的值! –
好吧!將嘗試。謝謝! –