头与之间的区别;尾递归

时间:2014-01-29 09:17:20

标签: java recursion difference

我正在尝试区分这两种递归策略。

我被告知的定义如下:

尾递归:如果在调用返回后没有必要进行调用,则调用是尾递归的,即当调用返回时,返回的值立即从调用函数返回

Head Recursion:当函数的第一个语句是递归调用时,调用是头递归的。

1 个答案:

答案 0 :(得分:27)

head recursion中,递归调用在它发生时,在函数中的其他处理之前(想想它发生在函数的顶部或头部)。

tail recursion中,它是相反的 - 处理发生在递归调用之前。在两种递归样式之间进行选择可能看起来是随意的,但选择可能会产生重大影响。

在路径开头具有单个递归调用的路径的函数使用所谓的头递归。先前展览的阶乘函数使用头部递归。一旦确定需要递归,它首先要做的是用递减的参数调用自身。 在路径末尾使用单个递归调用的函数使用尾递归。 Refer this article

示例递归:

public void tail(int n)         |     public void head(int n)
{                               |     {
    if(n == 1)                  |         if(n == 0)
        return;                 |             return;
    else                        |         else
        System.out.println(n);  |             head(n-1);
                                |
    tail(n-1);                  |         System.out.println(n);
}                               |     }

如果递归调用发生在方法的末尾,则称为tail recursion。尾递归是similar to a loopmethod executes all the statements before jumping into the next recursive call

如果递归调用发生在beginning of a method, it is called a head recursionmethod saves the state before jumping into the next recursive call