tags:

views:

319

answers:

3

I just want to know , is it possible to convert this recursive function to non recursive functions

unsigned Parser::Not(unsigned eff)
{
  if (eff == 0) return 1;

  if (eff == 1) return 0;

  Node rn(ri.get_key(eff));

  rn.t_branch_id = Not(rn.t_branch_id);
  rn.f_branch_id = Not(rn.f_branch_id);

  return CodeRuleNode(rn);
}
+5  A: 

Yes. You can convert any recursive function to a non-recursive function by implementing your own stack to keep track of state.

LBushkin
A: 

Any recursive function can be written non-recursively. However, you will need to use a stack or other data structure to keep track of which nodes you have visited.

Dietrich Epp
+1  A: 

It's possible, yes. Without a parent reference in the Node class, though, it will be difficult, and require a vector of current nodes (emulating the stack). If you can alter the Node class to include a reference to the parent, this will make iterating much easier, as the emulated stack is implicit in your tree definition.

However, generating a tree depth-first like this is a perfect job for recursion, as it's much more intuitive to read and write, and therefore less prone to bugs.

Medivh