新手在Groovy /遍历树中使用递归?

时间:2012-10-29 18:32:05

标签: recursion groovy

在我们当前的应用程序中,我们需要遍历树并捕获特定设备(和子设备)上的所有操作员。设备上可能有子设备,上面还有特定的操作符。

由于我是Groovy中使用递归的新手,我想知道我是否正确行事......? 是否有任何指针可以帮助我学习更好的做事方式?

def listOperators(device) {
    // list with all operator id's
    def results = []

    // closure to traverse down the tree
    def getAllOperators = { aDevice->
        if(aDevice) {
            aDevice.operators.each { it ->
                results << it.id
            }
        }
        if (aDevice?.children) {
            aDevice.children.each { child ->
                results << owner.call(child)
            }
        }
    }

    // call the closure with the given device
    getAllOperators(device)

    // return list with unique results
    return results.unique()
}

1 个答案:

答案 0 :(得分:4)

有几点需要注意:

  • 通过owner进行递归调用并不是一个好主意。如果调用嵌套在另一个闭包中,owner的定义会发生变化。它容易出错,与使用名称相比没有任何优势。当闭包是局部变量时,将其分解为闭包的声明和定义,因此名称在范围内。 E.g:

    def getAllOperators
    getAllOperators = { ...

  • 您将运算符追加到递归闭包之外的结果列表中。但是您还要将每个递归调用的结果附加到同一个列表中。附加到列表可以存储每个递归调用的结果,但不能同时存储两者。

这是一个更简单的选择:

def listOperators(device) {
    def results = []
    if (device) {
        results += device.operators*.id
        device.children?.each { child ->
            results += listOperators(child)
        }
    }
    results.unique()
}