[英]Why is my Binary Search Tree Delete not working?
二進制搜索樹可能需要一個大型程序,因此我決定不發布其余代碼。 我收到一些空指針異常,因為我認為我不明白在刪除函數中的何處放置花括號。 誰能幫助我找到問題並解釋原因? 底部的I / O:
// other functions above
public void delete(int key) {
LinkNode x = firstNode;
LinkNode temp = search(x, key);
if(temp == null) {
System.out.println("delete " + key + " - not found.");
return;
}
LinkNode y = delete(temp); // line 252
System.out.println("deleted " + y.key + ".");
}
private LinkNode delete(LinkNode x) {
LinkNode t = firstNode;
if(x.left == null || x.right == null) {
t = x;
} else {
t = successor(x);
}
if(t.left != null) {
x = t.left;
} else {
x = t.right;
}
if(x != null) {
x.parent = t.parent;
}
if(t.parent == null) {
firstNode = x;
} else if(t == t.parent.left) {
t.parent.left = x;
} else {
t.parent.right = x;
}
if(t != x) {
t.parent = x.parent; // line 280
}
return t;
}
這是一些輸入和輸出。 顯然我的其他功能似乎正常工作。
insert 3
inserted 3.
insert 5
inserted 5.
insert 2
inserted 2.
insert 20
inserted 20.
insert 100
inserted 100.
insert 42
inserted 42.
inorder
inorder traversal:
2 3 5 20 42 100
min
min is 2.
max
max is 100.
delete 3
deleted 5.
delete 42
Exception in thread "main" java.lang.NullPointerException
at Bst.delete(Bst.java:280)
at Bst.delete(Bst.java:252)
at prog.main(prog.java:52)
隨意詢問我的其他任何功能。 謝謝你的幫助
這應該是在邏輯上唯一可以分配未檢查的空指針的位置:
else {
x = t.right;
}
也許應該看起來像上面的代碼,並且是:
else if (t.right != null) {
x = t.right;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.