尾递归调用的时候不用在栈中保存以前运算的值,相比线性递归就节省了栈资源。好比计算阶乘:spa
线性递归:code
public int rescuvie(int i){
return i>1 ? i * rescuvie(i-1) : 1;
}
尾递归:blog
public int rescuvie(int i,int a){
return i>1 ? rescuvie(i-1,a*i) : 1;
}
尾递归计算5的阶乘,直接调用rescuvie(5,1)递归
尾递归的做用:资源
对于线性递归,它的递归过程:class
{5 * Rescuvie(4)}
{5 * {4 * Rescuvie(3)}}
{5 * {4 * {3 * Rescuvie(2)}}}
{5 * {4 * {3 * {2 * Rescuvie(1)}}}}
{5 * {4 * {3 * {2 * 1}}}}
{5 * {4 * {3 * 2}}}
{5 * {4 * 6}}
{5 * 24}
120
对于尾递归,它的递归过程:
rescuvie(5)
rescuvie(5, 1)
rescuvie(4, 5)
rescuvie(3, 20)
rescuvie(2, 60)
rescuvie(1, 120)
120
因此线性递归运行的过程当中,要存以前计算得出的值放在堆栈里。若是使用尾递归,能够节省栈资源