我在 Programming Interviews Exposed(第 3 版)中读到了递归,其中介绍了以下递归 factorial
函数:
int factorial(int n){
if (n > 1) { /* Recursive case */
return factorial(n-1) * n;
} else { /* Base case */
return 1;
}
}
在同一页的底部(第 108 页),他们讨论了尾递归函数:
Note that when the value returned by the recursive call is itself immediately returned, as in the preceding definition for
factorial
, the function is tail-recursive.
但这里真的是这样吗?函数中的最后一个调用是 *
调用,那么这个栈帧是否会被保留(如果我们不考虑编译器优化)?这真的是尾递归吗?
最佳答案
您可以将其重写为尾递归:
int factorial(int n){
return factorial2(n, 1);
}
int factorial2(int n, int accum) {
if (n < 1) {
return accum;
} else {
return factorial2(n - 1, accum * n);
}
}
关于c++ - 这个函数真的是尾递归的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115657/