【问题标题】:Java/Groovy Binary Tree InsertionJava/Groovy 二叉树插入
【发布时间】:2015-07-21 02:03:20
【问题描述】:

我正在尝试编写一个二叉树递归插入,但在过去的几个小时里我什么也没有。我要么收到 stackoverflow 错误,要么没有插入所有项目。

我想在我的树中插入这些值:

binaryTree.addNodeRecursion(new MNode(50, "fourth"))
binaryTree.addNodeRecursion(new MNode(25, "third"))
binaryTree.addNodeRecursion(new MNode(15, "second"))
binaryTree.addNodeRecursion(new MNode(10, "first"))
binaryTree.addNodeRecursion(new MNode(75, "fifth"))
binaryTree.addNodeRecursion(new MNode(85, "sixth"))

我想在不将根作为参数传递的情况下执行此操作。所以我的代码如下所示:

   public void addNodeRecursion(MNode newNode){

        if(root == null) {
            root = newNode
        }else{
            addRecurs(newNode); //this is the recursive function, it should not return a node object
        }
    }

请注意,我说的不是二叉搜索树,而是二叉树,其中元素顺序无关紧要。我关心如何插入元素。我想插入它们,如下所示:

1 Step: 
            50

2 Step:
            50
           /
          25

3 Step:
            50
           /  \
          25  15

4 Step:
            50
           /  \
          25  15
         /
        10

5 Step:
            50
           /  \
          25  15
         /  \
        10  75

6 Step: (now notice that I am going back to the sibling of the current parent)

             50
           /   \
          25    15
         /  \   /
        10  75 85

现在这是我的addRecurs 函数:

private void addRecurs(MNode newNode) {

    if(newNode == null) { return };

    if(root.leftNode == null){ //Step 2 if the left node is null assign it
        root.leftNode = newNode 
    }else{ //Else that means the right Node is null
        root.rightNode = newNode // Step 3 set the right node
        root = root.leftNode // the the parent to the left node
        addRecurs(newNode) // repeat
    }

};

它不起作用。

这可以在不跟踪或将父级存储在变量中的情况下完成吗?

【问题讨论】:

  • 你有一个简单完整的例子来说明你的问题吗?
  • 不,这只是我在空闲时间尝试做的事情。我自己提出了这个问题并试图解决它。主要问题是我想按照我在步骤中展示的特定顺序插入元素

标签: java groovy tree


【解决方案1】:

我建议您通过Heap 之类的方式支持您的树。基本上是一个基于数组的树结构,你似乎不需要排序部分,所以很简单。为了获得更好的答案,我们需要更多信息

【讨论】:

    【解决方案2】:

    你的问题是here的答案。

    static void addNode(node n)
    {
        if(root==null)
        {
            root = n;
        }
        else
        {
            node tmp = root; // save the current root
            if(root.getValue()>n.getValue())
            {
                root = root.leftLink;
                addNode(n);
            }
            else if(root.getValue()<n.getValue())
            {
                root = root.rightLink;
                addNode(n);
            }
            root = tmp; // put the root back to its original value
        }
        return;
    }
    

    【讨论】:

    • 就是这样。这里的人使用比较。我只是输入我的值而不进行比较。删除该代码中的 if 将不起作用。
    猜你喜欢
    • 2015-02-13
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多