Simply put, recursion is called itself. All recursion should have at least one basic condition, without recursion when basic conditions are met.
Give a recursive example:
1 int fact (int N) {2 if(n==1)3 return 1; 4 Else 5 return N*fact (N-1); 6 }
The execution of each recursive method is divided into two stages of forward and fallback, the above example calculates the factorial of 5, the result of the forward stage is:
(5* ((1)))
The fallback phase calculates the values in parentheses, in turn, by inward.
Applied to the program, respectively, corresponding to the stack and the stack. With this approach in mind, each call will be stacked out of the stack, which is inefficient. In addition, each recursive creation of a new stack when the recursion depth is too deep, it will cause a stack overflow, that is, can be divided into the creation of the stack of low memory situation. The method of tail recursion is presented.
Tail recursion, simply put, is to write the recursive statement to the last line and not participate in any calculations. Overwrite the previous example with the tail recursion as:
1 intFactintN) {2 if(n==1)3 return1;4 Else5 returnFact (n-1,n);6 } 7 8 intFactintNintM) {9 if(n==1)Ten returnM; One Else A returnFact (N-1, nM); -}
But this requires the compiler to optimize for tail recursion, each time it is reused or overwrites the stack of the original recursive method, rather than the new stack. Unfortunately, both Java and Python do not support tail-recursive optimizations, and Java's tail-recursive code is no different from normal recursion. Perhaps the JVM is trying to better output stack information in the event of an exception. Therefore, in Java, it is generally possible to use iterations instead of recursion.
Tail recursion and Java