2013-07-15 36 views
0

当试图在这BST根这样认识:二叉搜索树有问题与制作根节点

if (currentNode == null) { 
      currentNode = new BinaryNode(newInt); 
      System.out.println(currentNode); 
      System.out.println(newInt); 
      //System.out.println(newInt.getValue()); 
      System.out.println("Node Null, made root"); 
     }else{ 

中的println在那里进行调试。但是我有问题,因为这是输出:

[email protected] 
4 
Node Null, made root 
[email protected] 
6 
Node Null, made root 
[email protected] 
1 
Node Null, made root 
[email protected] 
3 
Node Null, made root 
[email protected] 
2 
Node Null, made root 
[email protected] 
8 
Node Null, made root 
[email protected] 
7 
Node Null, made root 
[email protected] 
5 
Node Null, made root 
[email protected] 
9 
Node Null, made root 

这让我觉得这是不承认(currentNode == NULL)像它应该。任何想法为什么?

全引擎收录:here

任何帮助,不胜感激:)

回答

1

你是不是分配给你的树的根。将其更改为:

if (root== null) { 
     root= new BinaryNode(newInt); 
2

的问题是,当你将currentNoderoot没有得到分配。

Java按值传递变量,这意味着将值或引用的副本传递到您的方法中。在这种情况下,currentNode(您的insertNode方法的正式参数)将传递由getRoot方法返回的root字段的副本。

为了解决这个问题,你应该一分为二的insertNode方法:

public void insert(int newInt); 

private BinaryNode insert(int newInt, BinaryNode node); 

公共方法应该没有getRoot参数(类插入在用户使用树应该永远不需要传递根目录,否则他们将能够通过在中间传递一个节点来打破你的树,其中的数字应该在不同的分支中)。

私有方法应返回旧节点或新节点。您应该使用这样的:

public void insert(int newInt) { 
    root = insert(newInt, root); 
} 

的方法本身应该返回新节点,如果node传入是null。当node不为空,该方法应该返回传入的节点。

至于outputList问题的话,你应该使用StringBuffer,而不是String构造输出。与不可变的String不同,StringBuilder是可变的。它可以让你改变它里面的字符串(使用append而不是+=)。

+0

谢谢,刚刚分配currentNode作为根,它的工作。在pastebin中看到的主要输出行不起作用 - 你能发现任何明显的错误吗?泰! – Sphyxx

+0

@Sphyxx同样的问题:字符串通过值传递,因此分配给'outString'对调用者没有任何影响。最简单的解决方案是'返回outString'。 –