Tail Recursion in Data Structures


Here we will see what is tail recursion. The tail recursion is basically using the recursive function as the last statement of the function. So when nothing is left to do after coming back from the recursive call, that is called tail recursion. We will see one example of tail recursion.

Example

 Live Demo

#include <iostream>
using namespace std;
void printN(int n){
   if(n < 0){
      return;
   }
   cout << n << " ";
   printN(n - 1);
}
int main() {
   printN(10);
}

Output

10 9 8 7 6 5 4 3 2 1 0

The tail recursion is better than non-tail recursion. As there is no task left after the recursive call, it will be easier for the compiler to optimize the code. When one function is called, its address is stored inside the stack. So if it is tail recursion, then storing addresses into stack is not needed.

We can use factorial using recursion, but the function is not tail recursive. The value of fact(n-1) is used inside the fact(n).

long fact(int n){
   if(n <= 1)
      return 1;
   n * fact(n-1);
}

We can make it tail recursive, by adding some other parameters. This is like below −

long fact(long n, long a){
   if(n == 0)
      return a;
   return fact(n-1, a*n);
}

Updated on: 27-Aug-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements