Let's say I have a structure to visit in a recursive way.
Pseudocode:
visit(node n)
{
if (n == visited)
return;
//do something
setVisited(n);
foreach child_node in n.getChildren(){
visit(child_node);
}
}
According to this thread tail recursion can occured when:
Tail recursion is basically when:
- there is only a single recursive call
- that call is the last statement in the function
In the pseudocode above the recursive call is the last statement, but there are multiple recursive call since the call happens inside a loop. I guess no tail recursion could be detected by the compiler.
My question is:
is there anyway to refactor the code above in order to make it tail recursive? I'm looking for a solution that doesn't remove the recursion, if there is one (es. I don't want to use a stack to simulate the recursion and transform that into an iterative function).
is this possible?
If the language is relevant, I'm using C++.