【问题标题】:Binary Tree: Why Does One Insert Method Work and the Other Not二叉树:为什么一种插入方法有效而另一种无效
【发布时间】:2013-09-25 16:38:22
【问题描述】:

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

不起作用的方法是:

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设置为新Node应该与将root.left/right设置为新Node相同。

【问题讨论】:

  • 第二个代码中的异常/问题是什么?我在第二个代码中没有看到 root == null 检查。在这种情况下,您不能插入第一个元素
  • @JohnnyAW:在他调用 insertNode(null, data) 的第一个代码中,这是行不通的。但我也需要一些时间才能得到它^^
  • @user2776326 我认为您的第二个代码有问题,因为如果 root 为空,那么它将如何与数据进行比较?
  • @ManuelM。我读错了,我认为第二个代码是错误的:) 但是你仍然不能在第二个代码中插入第一个元素:)
  • 不,你不能在第二个代码中添加根节点;-)

标签: java oop recursion binary-tree


【解决方案1】:

在您的第一个方法中,您将在 insertNode 方法中输入 null,但没有引用指针。因此你在insertNode方法中设置了root = new Node(),但是父节点不知道这些,它仍然指向null。

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

【讨论】:

  • 谢谢,我想我明白了。因此,从我收集到的信息中,Java 将值 null 传递给了参数,所以本质上我们得到了 insertNode(null, data),并且没有对 root.right/left 的引用。对吗?
【解决方案2】:

假设你递归调用方法insertNode(root, data),你必须确定root不是null,这意味着执行root = new Node(data);会创建一个可见性被限制为insertNode方法的对象。

如果不是,您可以将insertNode(data) 重写为非递归的,如果是null,则在其中创建root

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

【讨论】:

    猜你喜欢
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2012-03-05
    • 2022-08-10
    • 2020-10-25
    相关资源
    最近更新 更多