数据结构中的尾递归

在这里,我们将看到什么是尾递归。尾递归基本上是将递归函数用作函数的最后一条语句。因此,当从递归调用返回后无所事事时,这称为尾递归。我们将看到尾递归的一个示例。

示例

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

输出结果

10 9 8 7 6 5 4 3 2 1 0

尾递归优于非尾递归。由于递归调用后没有任务,编译器更容易优化代码。调用一个函数时,其地址存储在堆栈中。因此,如果是尾部递归,则不需要将地址存储到堆栈中。

我们可以使用递归的阶乘,但函数不是尾递归。事实(n-1)的值用于事实(n)中。

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

通过添加其他一些参数,我们可以使其尾部递归。这就像下面-

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