I am trying to build a simple tree like structure of objects and identify the depth level of each object. To do this i have created a recursive function but this function always returns the last results and not the expected total results. I probably store the results in a incorrect place.
def getStructure(anObject, level=0) {
def results = []
// [parent id, object id, level]
if(anObject.parent == null) {
results.add([0, anObject.id, level])
} else {
anObject.children?.each { child ->
results.add([anObject.parent.id, child.id, level])
}
// recursive call
anObject.children?.each { child ->
getStructure(child, level++)
}
results
}
In my test case i always get the latest run, so i guess the results = [] gets reinitialized every time. How do i store the results from a recursive function?
You need to add the results from the recursive call to the results. Instead of
try this: