Heisenbug Heisenbug - 26 days ago 9
C++ Question

Visit a tree or graph structure using tail recursion

Let's say I have a structure to visit in a recursive way.


visit(node n)
if (n == visited)

//do something
foreach child_node in n.getChildren(){


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++.

Answer Source

Tail recursion is immitating loops with no stack [or any other data structure], i.e. O(1) additional space.

AFAIK, the problem at hand, of tree/graph traversal [assume no parent field in each node] cannot be done at such a complexity [O(n) time, O(1) space], thus cannot be done with a single loop, with no stack. Therefore, no tail recursion refactoring is possible.

EDIT: The problem can be solves in O(1) space, but with O(n^2) time [which is double loop], as seen in this post.