2013-10-30 88 views
0

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

这里是NODE类。

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

,这里是与insert()方法BST(二进制Seatch树)类。

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

你能在代码中发现点点滴滴吗?

谢谢!

+2

您想命名以大写字母开头但不完全在大写字母中的类 - 保存最终变量的全部大写值。 –

+0

@ La-comadreja我会牢记这一点。谢谢。 –

回答

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

我正在研究将使这项工作的代码 – asaini007

+0

更新了我的答案......这个工作(在Eclipse中测试过)。有关于它的任何问题? – asaini007

+0

谢谢@ asaini007。这也适用于我。 任何想法,我哪里出错了? –

0

insert()方法应该将一个节点的子节点插入到树中,调用一个已经声明的Node作为参数。例如:

//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; 
} 
1

当然,树仍然是空的 - 你不分配任何东西给这个字段。 temp = tree后;和temp = node;只有温度改变了,而不是树。