将(二进制搜索树)的递归插入更改为非递归?

时间:2013-04-20 07:25:38

标签: java recursion while-loop binary-search-tree

我正在尝试将BST的递归插入方法更改为非递归(可能是While循环) 这种变化的原因是因为我想看看它是否可能。

以下是插入代码:

public void insert(String value)
{
    //The node is stored in the root
    root = insert(value,root);
}


private Character insert(String value,Character current)
{   
    if(current == null)
    {
        //Add the root if the tree empty 
     current = new Character(value);
    }
    else
        //If the value that we want to insert < root value, then keep going to left till 
        //it's empty then inserted at left end. Done by recursion 
        if(value.compareTo(current.getElement())<=-1)
        {
            current.setLeft(insert(value,current.getLeft()));
        }
        else
            //If the value that we want to insert > root value, then keep going to right till 
            //it's empty then inserted at right end. Done by recursion 
            if(value.compareTo(current.getElement())>=1)
            {
                current.setRight(insert(value,current.getRight()));
            }
            else
            {
                //Else, the number we want to insert in already in the tree
                System.out.println("Duplicate numbers inserted" + current.getElement());
            }
    //returning the node tree so that we store it in the root 
    return current;
}

我可以将此代码更改为非递归吗?

干杯

3 个答案:

答案 0 :(得分:1)

是的,您可以非递归地定义插入函数。

但是,要执行此操作,您的insert函数必须为BST定义按顺序遍历迭代器,这是递归定义的。

我相信有一种方法可以非递归地定义顺序遍历,但是根据实现,这可能是非常低效的。

BST本身基本上是递归定义的,并且递归地定义插入函数总是有效的。 (如果你真的需要它,我可以编写一些伪代码,但我认为它有点无意义,我不知道你的有序遍历迭代器的实现细节)

请不要忘记选择此作为答案: - )

答案 1 :(得分:1)

是的,但您需要稍微改变数据结构才能使其正常工作。 节点必须知道它的左子和右子。

算法如下所示:

current = root;
while(current != null){
   if(value.compareTo(current.getElement())<=-1)
   {
        current = current.left_child;
   }else if(value.compareTo(current.getElement())>=1){
        current = current.right_child;
   }else{
        // Duplication
   }
}

实际上之前有一些很好的例子,你可能想先检查一下:

答案 2 :(得分:0)

使用while循环

插入
npm i --save redux
相关问题