【问题标题】:Why is my Binary Search Tree Delete not working?为什么我的二叉搜索树删除不起作用?
【发布时间】:2018-04-28 00:59:38
【问题描述】:

二叉搜索树可能需要一个大程序,所以我决定不发布其余代码。我收到了一些空指针异常,因为我认为我不明白在删除函数中放置花括号的位置。谁能帮我找出问题并解释原因?底部 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)

请随时询问我的任何其他功能。感谢您的帮助

【问题讨论】:

  • 对于初学者,我会将您的辅助函数重命名为 deleteHelper 以使其更具可读性。
  • 调试此问题的一些建议:使用交互式调试器进入函数并找出变量为空的原因;在适当的位置添加assert 语句,以确保变量在您期望它们不为空时不为空。

标签: java nullpointerexception binary-search-tree


【解决方案1】:

这应该是唯一可以分配未检查空指针的逻辑可能位置:

else {
    x = t.right;
}

也许它应该看起来像上面的代码并且是:

else if (t.right != null) {
    x = t.right;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多