二叉树:为什么一个插入方法工作而另一个不工作

时间:2013-09-25 08:16:24

标签: java oop recursion binary-tree

我刚刚学习了二叉树,我尝试创建一个插入方法。我的第一种方法不起作用,我做了一些调整。它现在有效,但我不明白为什么以前的方法失败了。

不起作用的方法是:

if(root == null)
    {
        root = new Node(data);
    }
    else if(data < root.getData())
    {
        insertNode(root.getLeft(), data);
    }
    else
    {
        insertNode(root.getRight(), data);
    }

有效的方法是:

    if(data < root.getData())
    {
         if(root.getLeft() == null)
         {
             root.left = new Node(data);
         }
         else
         {
             insertNode(root.getLeft(), data);
         }
     }

     else
     {
         if(root.getRight() == null)
         {
             root.right = new Node(data);
         }
         else
         {
            insertNode(root.getRight(), data);
         }
     }

有关为何会出现这种情况的任何解释?因为我看到它的方式,root应该等于root.left,所以将root设置为新节点应该与将root.left / right设置为新节点相同。

2 个答案:

答案 0 :(得分:2)

在第一个方法中,您将null赋入insertNode方法,但没有引用指针。因此,您在insertNode方法中设置root = new Node(),但父节点不知道任何此类,它仍然指向null。

由于这是一些非常基本的Java理解,我建议阅读一些关于“java参数传递”的文章,例如: http://javadude.com/articles/passbyvalue.htm

答案 1 :(得分:0)

假设您递归地调用该方法insertNode(root, data),您必须确保root不是null,这意味着执行root = new Node(data);会创建一个可见性为限于insertNode方法。

如果没有,您可以将insertNode(data)重写为非递归,并在其root内创建null

public void insert(int data) {
    if(root == null){
        root = new Node(data);
    }
    else {
        Node current = root;
        Node previous;
        String from;
        while(current != null) {
            previous = current;
            if(data < current.getData()) {
                current = current.left();
                from = "left";
            }
            else {
                current = current.right();
                from = "right";
            }
        }
        current = new Node(data);
        if(from.equals("left")) {
            previous.left() = current;
        } else {
            previous.right() = current;
        }
    }
}
相关问题