java - 节点未添加到树中

标签 java tree

我一直在尝试使用 Java 创建一个整数二叉搜索树,但由于某种原因,我在向树添加新节点时出错了。

这是NODE 类。

class NODE
{
    NODE left = null, right = null;
    int info;
    public NODE(int x)
    {
        info = x;
    }
}

这是带有 insert() 方法的 BST(二叉搜索树)类。

class BST
{
    NODE tree = null;
    public void insert(int x)
    {
        NODE node = new NODE(x);
        NODE temp = tree;
        while(true)
        {
            if(temp == null)
            {
                temp = node;
                break;
            }
            else if(temp.info > x) temp = temp.left;
            else temp = temp.right;
        }
    }
    //other methods present here
}

由于我无法弄清楚的原因,insert() 方法出错了。

即使在调用 insert() 方法之后,对象 tree 仍会在其中携带 null

你能在代码中发现一些不稳定的地方吗?

谢谢!

最佳答案

NODE 类中使用递归 insert 方法(而不是像您那样利用无限循环):

public void insert(int x) {
        if(x < this.info) {
            if(this.left == null)
                this.left = new NODE(x);
            else
                this.left.insert(x);
        }
        else {
            if(this.right == null)
                this.right = new NODE(x);
            else
                this.right.insert(x);
        }
    }

您的 BST 类将具有以下 insert 方法(只需调用另一个 insert 方法):

public void insert(int x) {
    if(tree == null)
        tree = new NODE(x);
    else
        tree.insert(x);
}

主要的 insert 方法位于 NODE 类中,因为它必须在树中的节点上递归地调用自身。

关于java - 节点未添加到树中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687811/

相关文章:

java - 如果在类级别设置了 Include.NON_NULL,则 Jackson 序列化 NULL 属性值

java - 使用 HTTP Java 客户端执行异步请求时如何处理错误?

java - Java中HTTPRequest获取数据

javascript - 如何使用具有父子关系的 JSON 数据创建带复选框的树?

algorithm - 红黑树删除未知行为

java - 具有可变对象 Java 的不可变数组

时间之前的 Java 日期在生产中无法按预期工作

python - 为什么我得到相同的图表?

python - 树上的高效相等函数

PHP/MySQL 构建树形菜单