fresh42juice
fresh42juice

Reputation: 117

How can I eliminate tail recursion in the following function (from two recursive calls to one)?

I have the following function:

void treetraverse (tnode *node)
{
   if (node == NULL)
   {
      return;
   }
   fprintf(stdout,"%d",node->val);
   if (node-> d == 'L')
   {
      treetraverse(node->r);
      treetraverse(node->l);
    }
    else
    {
      treetraverse(node->l);
      treetraverse(node->r);
     }
}

Where d is direction which could be 'L' or 'R'. And node->r and node->l is right and left child of a node respectively. I am trying to remove tail recursion from this so that it is functionally equivalent - it makes two recursive function calls now but I want it to make one. How can I rewrite the function such that it achieves this goal? Thank you.

Upvotes: 0

Views: 83

Answers (1)

The most straight-forward approach would be something along the lines of

void treetraverse (tnode *node)
{
  do
  {

   if (node == NULL)
   {
      return;
   }
   fprintf(stdout,"%d",node->val);

   tnode *node1;
   tnode *node2;

   if (node-> d == 'L')
   {
      node1 = node->r;
      node2 = node->l;
    }
    else
    {
      node1 = node->l;
      node2 = node->r;
     }

    treetraverse(node1);
    node = node2;

    }
    while (true);
}

Upvotes: 1

Related Questions