The Wayback Machine - https://web.archive.org/web/20240817152155/https://www.geeksforgeeks.org/tail-vs-non-tail-recursion/
Open In App

Tail vs. Non-Tail Recursion

Last Updated : 06 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  • Tail recursion is defined by having the recursive call as the last operation in the function before returning

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

  • While non-tail recursion involves other operations after the recursive call

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:

  • In tail recursion, the base case is typically handled at the end of the function.
  • whereas in non-tail recursion, it can be handled before making the recursive call. 

3) Stack Usage:

  • Tail recursion can often be optimized to use a constant amount of stack space, as the current function’s stack frame can be reused for the recursive call.
  • Non-tail recursion typically uses more stack space because each recursive call creates a new stack frame. 

4) Optimization Potential:

  • Tail recursion has the potential to be optimized by compilers/interpreters for tail call elimination, which improves stack space efficiency.
  • Non-tail recursion may not benefit from this optimization. 

5) Examples:

  • Examples of tail recursion include factorial calculations and some tree traversal algorithms.
  • Non-tail recursion is common in algorithms like Fibonacci sequence generation and recursive algorithms without tail call optimization.

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.



Similar Reads

Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Tail recursion to calculate sum of array elements.
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the stat
3 min read
Tail Recursion in Python Without Introspection
These are the special type of recursive functions, where the last statement executed inside the function is the call to the function itself. Advantages of implementing Tail Recursive functionIn this concept, the compiler doesn't need to save the stack frame of the function after the tail-recursive call is executed.It uses less memory as compared to
4 min read
What is Tail Recursion
Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following C++ function print() is tail recursive. C/C++ Code // An example of tail recursive function void print(int n) { if (n < 0
8 min read
Tail Recursion for Fibonacci
Write a tail recursive function for calculating the n-th Fibonacci number. Examples : Input : n = 4 Output : fib(4) = 3 Input : n = 9 Output : fib(9) = 34 Prerequisites : Tail Recursion, Fibonacci numbersA recursive function is tail recursive when the recursive call is the last thing executed by the function. Writing a tail recursion is little tric
4 min read
Tail Recursion in Python
Tail recursion is a special case of recursion where the recursive call is the last operation in the function. Therefore, the function returns the result of the recursive call directly, without performing any additional computation after the call. In some languages, tail-recursive functions can be transformed into iterative loops to avoid growing th
3 min read
Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursion and stack) In inorder traversal, we follow "left
11 min read
Sorted insert in a doubly linked list with head and tail pointers
A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to ri
10 min read
What is a Proper Tail Call?
What is a Proper Tail Call? Proper tail calls (PTC) is a programming language feature that enables memory-efficient recursive algorithms. Tail call optimization is where you can avoid allocating a new stack frame for a function because the calling function will simply return the value it gets from the called function. The most common use is tail-re
5 min read
Tail Call Optimisation in C
In C programming, Tail Call Optimization (TCO) is a technique that eliminates the need for an additional stack frame to store the data of another function by reusing the current function's stack frame. This optimization technique is only possible for tail function calls. What is Tail Call?The tail call is the type of function call where another fun
4 min read
QuickSort Tail Call Optimization (Reducing worst case space to Log n )
Prerequisite : Tail Call Elimination In QuickSort, partition function is in-place, but we need extra space for recursive function calls. A simple implementation of QuickSort makes two calls to itself and in worst case requires O(n) space on function call stack. The worst case happens when the selected pivot always divides the array such that one pa
12 min read
Tail Call Elimination
We have discussed (in tail recursion) that a recursive function is tail recursive if the recursive call is the last thing executed by the function. C/C++ Code // An example of tail recursive function void print(int n) { if (n < 0) return; cout << " " << n; // The last executed statement is recursive call print(n-1); } Java
10 min read
Count of integers up to N which are non divisors and non coprime with N
Given an integer N, the task is to find the count of all possible integers less than N satisfying the following properties: The number is not coprime with N i.e their GCD is greater than 1.The number is not a divisor of N. Examples: Input: N = 10 Output: 3 Explanation: All possible integers which are less than 10 and are neither divisors nor coprim
5 min read
Minimum increments of Non-Decreasing Subarrays required to make Array Non-Decreasing
Given an array arr[] consisting of N integers, the task is to find the minimum number of operations required to make the array non-decreasing, where, each operation involves incrementing all elements of a non-decreasing subarray from the given array by 1. Examples: Input: arr[] = {1, 3, 1, 2, 4} Output: 2 Explanation: Operation 1: Incrementing arr[
4 min read
Count numbers in a given range having prime and non-prime digits at prime and non-prime positions respectively
Given two integers L and R, the task is to find the count of numbers in the range [L, R] having prime digits at prime positions and non-prime digits at non-prime positions. Examples: Input: L = 5, R = 22 Output: 7Explanation: The numbers 6, 8, 9, 12, 13, 15, and 17 have prime digits at prime positions and non-prime digits at non-prime positions. In
15 min read
Split an array into minimum number of non-increasing or non-decreasing subarrays
Given an array arr[] of size N, the task is to split the given array into a minimum number of subarrays such that elements of each subarray are either in non-increasing order or non-decreasing order. Examples: Input: arr[] = {2, 3, 9, 5, 4, 6, 8}Output: 3Explanation: Split the array into 3 subarrays following three subarrays: {2, 3, 9} (non-decreas
10 min read
Pendant Vertices, Non-Pendant Vertices, Pendant Edges and Non-Pendant Edges in Graph
Pre-requisites: Handshaking theorem. Pendant Vertices Let G be a graph, A vertex v of G is called a pendant vertex if and only if v has degree 1. In other words, pendant vertices are the vertices that have degree 1, also called pendant vertex. Note: Degree = number of edges connected to a vertex In the case of trees, a pendant vertex is known as a
7 min read
Find indices having at least K non-increasing elements before and K non-decreasing elements after them
Given an array arr[] of size N and an integer K, the task is to find all the indices in the given array having at least K non-increasing elements before and K non-decreasing elements after them. Examples: Input: arr[] = {1, 1, 1, 1, 1}, K = 0Output: 0 1 2 3 4Explanation: Since K equals 0, every index satisfies the condition. Input: arr[] = {1, 2, 3
6 min read
Minimize Operation to Make Array Non-decreasing or Non-increasing
Given an integer array arr[]. In one operation, you can choose an index i and either increment or decrement arr[i] by 1. The task is to find the minimum number of operations needed to make arr either non-decreasing or non-increasing. Example: Input: arr = [3, 2, 4, 5, 0]Output: 4Explanation: One possible way to turn arr into non-increasing order is
8 min read
The Great Tree-List Recursion Problem.
Asked by Varun Bhatia. Question: Write a recursive function treeToList(Node root) that takes an ordered binary tree and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The”previous” pointers should be stored in the “small” field and the “next” pointers should be stored in the “large” field. The list sho
1 min read
Inorder Tree Traversal without recursion and without stack!
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. 1. Initialize current as root 2. While current
9 min read
Practice questions for Linked List and Recursion
Assume the structure of a Linked List node is as follows. C/C++ Code struct Node { int data; struct Node *next; }; // This code is contributed by SHUBHAMSINGH10 C/C++ Code struct Node { int data; struct Node *next; }; Java Code static class Node { int data; Node next; }; // This code is contributed by shubhamsingh10 C/C++ Code class Node: def __ini
11 min read
Practice Questions for Recursion | Set 1
Explain the functionality of the following functions. Question 1 C/C++ Code int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } C/C++ Code int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } Java Code static int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } C/C
5 min read
Practice Questions for Recursion | Set 2
Explain the functionality of the following functions. Question 1 C/C++ Code /* Assume that n is greater than or equal to 1 */ int fun1(int n) { if (n == 1) return 0; else return 1 + fun1(n / 2); } Java Code /* Assume that n is greater than or equal to 1 */ static int fun1(int n) { if (n == 1) return 0; else return 1 + fun1(n / 2); } C/C++ Code # As
3 min read
Practice Questions for Recursion | Set 4
Question 1 Predict the output of the following program. C/C++ Code #include <iostream> using namespace std; void fun(int x) { if(x > 0) { fun(--x); cout << x <<" "; fun(--x); } } int main() { int a = 4; fun(a); return 0; } // This code is contributed by SHUBHAMSINGH10 C/C++ Code #include<stdio.h> void fun(int x)
6 min read
Practice Questions for Recursion | Set 5
Question 1Predict the output of the following program. What does the following fun() do in general? C/C++ Code #include <iostream> using namespace std; int fun(int a, int b) { if (b == 0) return 0; if (b % 2 == 0) return fun(a + a, b/2); return fun(a + a, b/2) + a; } int main() { cout << fun(4, 3) ; return 0; } // This code is contribut
5 min read
Practice Questions for Recursion | Set 7
Question 1 Predict the output of the following program. What does the following fun() do in general? C/C++ Code #include <iostream> using namespace std; int fun(int n, int* fp) { int t, f; if (n <= 2) { *fp = 1; return 1; } t = fun(n - 1, fp); f = t + *fp; *fp = t; return f; } int main() { int x = 15; cout << fun(5, &x) <<
4 min read
Print 1 to 100 in C++ Without Loops and Recursion
We can print 1 to 100 without using loops and recursion using three approaches discussed below: 1) Template Metaprogramming: Templates in C++ allow non-datatypes also as parameters. Non-datatype means a value, not a datatype. Example: C/C++ Code // CPP Program to print 1 to 100 // without loops and recursion #include <iostream> using namespac
3 min read
Print ancestors of a given binary tree node without recursion
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.For example, consider the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Following are different input keys and their ancestors in the above tree Input Key List of Ancestors ------------------------- 1 2 1 3 1 4 2 1 5 2 1
15 min read
Juggler Sequence | Set 2 (Using Recursion)
Juggler Sequence is a series of integer number in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation : [Tex]a_{k+1}=\begin{Bmatrix} \lfloor a_{k}^{1/2} \rfloor & for \quad even \quad a_k\\ \lfloor a_{k}^{3/2} \rfloor & for \q
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg