我在將 Treapnode 插入 Treap 時遇到問題。它接受 3 個參數。添加(E 鍵,P 優先級,treapnode x)。我嘗試了很多方法,但總是出現空指針異常。我嘗試檢查左右樹中的空情況。private TreapNode add (E key, P priority, TreapNode x) throws ElementFoundException { // For You To Complete int compare = key.compareTo(x.element()); if (x == null){ return new TreapNode(key, priority); } //root is larger than the key else if (compare == 0) { throw new ElementFoundException("Element was found, and tree was not changed."); } else if (compare < 0) { if (x.left() == null) { //TreapNode y = new TreapNode(key, priority); TreapNode y = x.left; x.left = y.right; y.right = x; return y; } else { x.left = add(key, priority, x.left()); } } //root is smaller than the key else if (compare > 0) { if (x.right() == null) { //TreapNode y = new TreapNode(key, priority); TreapNode z = x.right; x.right = z.left; z.left = x; return z; } } return x;}
1 回答

MM們
TA貢獻1886條經驗 獲得超2個贊
這是你做錯了x.right()。情況也是如此x.left()
if (x.right() == null) {
? ? ? ? //TreapNode y = new TreapNode(key, priority);
? ? ? ? TreapNode z = x.right; // z = null
? ? ? ? x.right = z.left;? // z.left will throw NPE
應該
if (x.right() == null) {
? ?x.right() = new TreapNode(key, priority);
? ?return x; // return parent node?
}
另外,我認為這也是一個錯誤的比較,int不能null但是Integer類可以
int compare = key.compareTo(x.element());? //comoareTo return an int?
if (x == null){? // does not make sense to compare and int type to Object type
? ....
}
添加回答
舉報
0/150
提交
取消