Java 头尾递归的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21426688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The difference between head & tail recursion
提问by Scarl
I'm trying to get the difference between these 2 recursive strategies.
我试图找出这两种递归策略之间的区别。
The definition I was told is the following:
我被告知的定义如下:
Tail Recursion:A call is tail-recursive if nothing has to be done after the call returns i.e. when the call returns, the returned value is immediately returned from the calling function
尾递归:如果在调用返回后无需执行任何操作,则调用是尾递归的,即当调用返回时,返回值立即从调用函数返回
Head Recursion:A call is head-recursive when the first statement of the function is the recursive call.
头递归:当函数的第一条语句是递归调用时,调用是头递归的。
采纳答案by Java Curious ?
In head recursion
, the recursive call, when it happens, comes before other processing in the function (think of it happening at the top, or head, of the function).
在 中head recursion
,递归调用发生在函数中的其他处理之前(想想它发生在函数的顶部或头部)。
In tail recursion
, it's the opposite—the processing occurs before the recursive call. Choosing between the two recursive styles may seem arbitrary, but the choice can make all the difference.
在 中tail recursion
,情况正好相反——处理发生在递归调用之前。在两种递归风格之间进行选择似乎是随意的,但选择可以产生很大的不同。
A function with a path with a single recursive call at the beginning of the path uses what is called head recursion. The factorial function of a previous exhibit uses head recursion. The first thing it does once it determines that recursion is needed is to call itself with the decremented parameter. A function with a single recursive call at the end of a path is using tail recursion. Refer this article
具有在路径开头具有单个递归调用的路径的函数使用所谓的头递归。先前展示的阶乘函数使用头递归。一旦确定需要递归,它所做的第一件事就是用递减的参数调用自己。在路径末尾具有单个递归调用的函数使用尾递归。 参考这篇文章
Example Recursion :
示例递归:
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);
} | }
If the recursive call occurs at the end of a method, it is called a tail recursion
. The tail recursion is similar to a loop
. The method executes all the statements before jumping into the next recursive call
.
如果递归调用发生在方法的末尾,则称为 a tail recursion
。尾递归是similar to a loop
。的method executes all the statements before jumping into the next recursive call
。
If the recursive call occurs at the beginning of a method, it is called a head recursion
. The method saves the state before jumping into the next recursive call
.
如果递归调用发生在beginning of a method, it is called a head recursion
. 的method saves the state before jumping into the next recursive call
。