简体   繁体   English

为什么我的二进制搜索树删除功能不起作用?

[英]Why is my Binary Search Tree Delete not working?

Binary Search Tree can require a big program, so I decided not to post the rest of the code. 二进制搜索树可能需要一个大型程序,因此我决定不发布其余代码。 I'm getting some null pointer exceptions, because I think I'm not understanding where to put a curly brace within my delete function. 我收到一些空指针异常,因为我认为我不明白在删除函数中的何处放置花括号。 Can anyone help me find the problem and explain why? 谁能帮助我找到问题并解释原因? I/O at the bottom: 底部的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;
}

Here is some input and output. 这是一些输入和输出。 It definitely seems like my other functions are working correctly. 显然我的其他功能似乎正常工作。

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)

Feel free to ask for any of my other functions. 随意询问我的其他任何功能。 Thanks for any help 谢谢你的帮助

This should be the only logically possible place where the unchecked null-pointer could be assigned: 这应该是在逻辑上唯一可以分配未检查的空指针的位置:

else {
    x = t.right;
}

Perhaps it should look like the code above and be: 也许应该看起来像上面的代码,并且是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM