The various answers proposed so far, which sum up to "do it outside of recurse
", are fine. But if you're keen to do it inside recurse
, that's not hard either (just marginally less efficient):
function recurse(a, _toplevel=True):
for child in a.childs:
recurse(child, False)
if _toplevel:
print "Recursion done!"
The leading _
in the name of the _toplevel
argument indicates it's private, so callers know not to pass it.
Similar solutions involve keeping track of the level of recursion (not just whether it's top level or not, but "how deep you are" in general):
function recurse(a, _level=0):
for child in a.childs:
recurse(child, _level + 1)
if _level == 0:
print "Recursion done!"
While precious in other cases (e.g. printing out nested structures with indents) it's not needed here (and there's another marginal loss of efficiency compared with the first solution I gave, based on the _toplevel
boolean).