二进制搜索树在创建根节点时遇到问题

时间:2013-07-15 10:16:19

标签: java binary-search-tree

尝试在此BST中创建一个root:

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用于调试。但是我遇到了问题,因为这是输出:

BinaryNode@7004ba66
4
Node Null, made root
BinaryNode@4669b7fe
6
Node Null, made root
BinaryNode@46aea8cf
1
Node Null, made root
BinaryNode@74ccd249
3
Node Null, made root
BinaryNode@3301f287
2
Node Null, made root
BinaryNode@44d9973a
8
Node Null, made root
BinaryNode@29578426
7  
Node Null, made root
BinaryNode@30a4effe
5
Node Null, made root
BinaryNode@1c8825a5
9
Node Null, made root

这让我觉得它没有像它应该那样识别(currentNode == null)。有什么想法吗?

完整的pastebin:here

任何帮助都非常感谢:)

2 个答案:

答案 0 :(得分:2)

问题在于,当您指定currentNode时,root不会被分配。

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

要解决此问题,您应该将insertNode方法分成两部分:

public void insert(int newInt);

private BinaryNode insert(int newInt, BinaryNode node);

公共方法应该在没有getRoot参数的情况下使用(类中插入树的用户永远不需要传递根,否则他们可以通过在中间传递一个节点来破坏你的树数字应该在不同的分支中。)

私有方法应该返回旧节点或新节点。你应该像这样使用它:

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

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

outputList问题而言,您应该使用StringBuffer而不是String来构建输出。与String不可变的StringBuilder不同,append是可变的。它允许您更改其中的字符串(使用+=而不是{{1}})。

答案 1 :(得分:1)

您没有分配到树的根目录。将其更改为:

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