节点未添加到树中

时间:2013-10-30 15:58:04

标签: java tree

我一直在尝试使用Java创建integer binary search tree,出于某种原因,我在向树中添加新节点时出错了。

这是NODE类。

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

这是使用BST方法的insert()(二进制Seatch Tree)类。

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()方法出错了。

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

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

谢谢!

3 个答案:

答案 0 :(得分:4)

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

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类中,因为它必须以递归方式在树中的节点上调用自身。

答案 1 :(得分:1)

当然树仍为空 - 您不会为此字段指定任何内容。 在temp = tree之后;和temp = node;只有临时改变,而不是树。

答案 2 :(得分:0)

insert()方法应该将节点的子节点插入树中,将已声明的Node作为参数调用。 e.g:

//Returns true/false depending on whether the insert is successful
public boolean insert(int x, Node node, boolean leftChild) {      
    if (node == null) return false;
    Node child = new Node(x);
    if (leftChild) {
        if (node.left != null) return false;
        node.left = child;
    } else {
        if (node.right != null) return false;
        node.right = child;
    }
    return true;
}