Java – the difference between head and tail recursion
See English answers > what is tail recurrence? 20
The definitions I was told are as follows:
Tail recursion: if there is no operation after the call returns, the call is recursive, that is, when the call returns, the returned value is immediately returned from the calling function
Head recursion: when the first statement of a function is a recursive call, the call is head recursion
Solution
In head recursion, when a recursive call occurs, it occurs before other processing in the function (it is considered to occur at the top or head of the function)
In tail recursion, the opposite is true - processing occurs before the recursive call The choice between the two recursive styles may be arbitrary, but the choice may be different
Functions that use a single recursive call at the beginning of the path use so - called header recursion Previously exhibited factorial functions using header recursion The first thing it needs to determine recursion is to call itself with decreasing parameters A single recursive function called at the end of the path uses 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 a recursive call occurs at the end of a method, it is called tail recursion Tail recursion is similar to loops This method executes all statements before jumping to the next recursive call
If a recursive call occurs at the beginning of a method, it is called head recursion This method saves the state before jumping to the next recursive call