Open In App

Tail vs. Non-Tail Recursion

Tail recursion and Non-tail recursion are two types of recursive functions in computer programming. In this post we will deep dive into what are the major differences between the tail and non-tail recursion.

1) Definition:

function factorial (currentNumber , previousMultiplication):



if currentNumber is less or equal to 0 then

return previousMultiplication



else

return factorial( currentNumber – 1, currentNumber * previousMultiplication ) // Tail Recursion

end

end

function factorial ( n ):

if n is less or equal to 0 then

return 1

else

return n * factorial ( n – 1 ) // Non-Tail Recursion

end

end

2) Base Case Handling:

3) Stack Usage:

4) Optimization Potential:

5) Examples:

6) Which One is Better? Tail or Non-Tail Recursion?

Tail recursion” is considered better than non-tail recursion because tail recursive functions can be optimized by modern compilers.

In summary, the key difference between tail and non-tail recursion lies in where the recursive call occurs within the function and how it impacts stack space usage and potential optimizations. Tail recursion is often preferred when possible due to its potential for stack space optimization.

7) Can We Convert a Non-tail Recursion to a Tail Recursion?

The answer is “YES“, We can convert any Non-tail recursive function to a Tail recursive function by passing additional parameters to maintain the state of the recursive call.

Difference Between Tail and Non-Tail Recursion:

Below is the comparison of these two types in tabular format:

Feature Tail Recursion Non-Tail Recursion
Definition A recursive function is said to be tail-recursive if the recursive call is the last thing done in the function before returning. A recursive function is said to be non-tail-recursive if the recursive call is not the last thing done in the function before returning.
Base Case Handling Usually, the base case is handled at the end of the function after the recursive call. Usually, the base case is handled before making the recursive call.
Stack Usage Typically, tail recursion can be optimized by compilers/interpreters to use a constant amount of stack space. Typically, non-tail recursion uses more stack space because each recursive call creates a new frame on the call stack.
Optimization Potential Can be optimized for tail call elimination, improving stack space efficiency. May not be optimized for tail call elimination, which can lead to stack overflow errors.
Examples Factorial function, some tree traversals, mutual recursions with multiple recursive calls. Fibonacci sequence, recursive algorithms without the tail call optimization.

Article Tags :