【问题标题】:how to construct a tree from a tree without recursion如何在没有递归的情况下从树构造树
【发布时间】:2017-05-28 21:28:16
【问题描述】:

我有一棵芒果树,对于每个我想应用处理将它们变成苹果的项目,我如何编写一个方法(在 Java 中会很好),它占据芒果树元素的顶部和不递归返回苹果树的顶部。

通过递归,我有这样的东西:

Apple transform(Mangoe ma){      
    //Construct an apple from some modified mangoes properties
    Apple ap = new Apple(...);  
    List<Apple> apChildren = new ArrayList<Apple>();
    for(Mangoe maChild:ma.getChildren())
        children.add(transform(maChild));  
    ap.setChildren(children);  
    return ap;
}

如何使用不递归的方法重复此行为??

编辑: 我正在考虑这个算法来解决这个问题:

List<Mangoe> itemsToTreat = new ArrayList<Mangoe>();
itemsToTreat.add(ma);

while(itemsToTreat!=null){
     //Apply treatment
     //it's impossible to set the child of a created apple without recursion         

     //get the direct children of itemsToTreat
     itemsToTreat = getDirectChildrenOfItemsToTreat(itemsToTreat);


}

【问题讨论】:

  • 在大多数情况下,您可以将递归调用替换为循环和某种堆栈,例如看看here。毕竟,递归方法调用也是如此:它们只是将同一方法的另一个调用连同参数等一些信息放在调用堆栈中。
  • 我不确定你所说的递归是什么意思。您可以借助堆分配的数据结构将递归过程编写为迭代循环,以处理递归而不是系统堆栈。如果没有任何类型的递归过程,你就无法做到这一点,因为这将要求树的每个节点都不能有多个子节点,因此需要一个链表。
  • 如果您使用Tree 结构,恐怕您将不得不使用递归,无论是隐藏的还是显式的。例如,如果您使用TreeSet,您可能会得到它的迭代器并使用while 循环遍历所有元素。然而在迭代器内部会有多次递归调用TreeMap.successor(Entry&lt;K,V&gt; t)方法

标签: java recursion tree


【解决方案1】:

由于我现在对Java不是很流利,所以我会使用一些类似Java的伪代码和一些解释。该问题可以通过用户定义的堆栈来解决,如下所示。关键是存储一些信息将生成的结果存储在哪里,这是在递归实现中的调用堆栈上隐式完成的;这是通过以下辅助类完成的,该类存储了足够的信息。

class AugmentedMangoe
{
    public Mango iMangoe;      // Mangoe to convert
    public Apple iParentApple; // place where to add it as child after conversion

    public AugmentedMangoe(Mangoe iMangoe, Apple iParentApple)
    {
        iMangoe = iMangoe;
        iParentApple = iParentApple;
    }
}

实际的迭代过程是通过iStack 完成的,它对递归进行建模。

Apple transform(Mangoe ma)
{
    Apple Result = null;
    Stack<AugmentedMangoe> iStack = new Stack<AugmentedMangoe>();
    iStack.push(new AugmentedMangoe(ma, null));
    while (iStack.hasElements())
    {
        // get current Mangoe
        Mangoe iCurrentMangoe = iStack.pop();

        // convert Mangoe to Apple and save it
        Apple iCurrentApple = new Apple(iCurrentMangoe.iMangoe);

        // store the converted root, which is done only in the first iteration
        Result = null != Result ? Result : iCurrentApple;

        // put children to the stack
        for(Mangoe iChild:iCurrentMangoe.iMangoe.getChildren())
            iStack.push(new AugmentedMangoe(iChild, iCurrentApple));

        // if we have stored where to put the converted object to, put it there
        if (null != iCurrentMangoe.iParentApple)
            iCurrentMangoe.iParentApple.addChild(iCurrentApple);
    }
    return Result:
}

不应该是Mango而不是Mangoe,应该是magnifera indica的意思吧?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    相关资源
    最近更新 更多