Tail recursion = recursion + iteration ?, Tail recursion
0 Introduction
It usually involves recursion and iteration. recursion is intuitive, but it occupies too much memory and time. iteration is fast, but it is not as concise and clear as recursive code. Can we combine the advantages of these two algorithms? The answer is yes. tail recursion provides such a mechanism.
What is tail recursion?
To put it simply, tail recursion is wearing the coat of "recursion", but has an "iteration" heart. It looks like recursion, but iteration is performed internally. The following is an example.
2. factorial example 2.1 first look at the factorial Iteration Algorithm:
2.2 let's look at the recursive algorithm of factorial:
2.3 Finally, let's look at the tail recursion algorithm of the factorial:
3 Fibonacci series example 3.1 Let's first look at the iterative algorithm of the Fibonacci series:
3.2 let's look at the recursive algorithm of the Fibonacci series:
3.3 Finally, let's look at the ending recursive algorithm of the Fibonacci series:
Summary
As shown in the example, tail recursion always carries an "Iteration variable" to the depth of recursion, which is equivalent to side recursion and edge computing. When recursion is completed, the results are also calculated. It is worth mentioning that tail recursion only uses the shell of recursion, and its essence is still iterative. Therefore, efficiency should be similar to iteration.