如何在没有递归的情况下从树构造树

时间:2017-01-13 13:31:26

标签: java recursion tree

我有一个Mangoes项目树,对于我想要应用治疗将它们变成苹果的每个项目,我怎样才能编写一个方法(在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);


}

1 个答案:

答案 0 :(得分:0)

由于我目前不熟悉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是什么意思?