The Wayback Machine - https://web.archive.org/web/20240828040544/https://www.geeksforgeeks.org/recursion-algorithms/
Open In App

Recursion Algorithms

Last Updated : 03 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
49.57%
50.6K

Recursion is technique used in computer science to solve big problems by breaking them into smaller, similar problems. The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily.

Recursion-Algorithm.png

What is Recursion?

Recursion is a programming technique where a function calls itself within its own definition. This allows a function to break down a problem into smaller subproblems, which are then solved recursively.

How Does Recursion Work?

Recursion works by creating a stack of function calls. When a function calls itself, a new instance of the function is created and pushed onto the stack. This process continues until a base case is reached, which is a condition that stops the recursion. Once the base case is reached, the function calls start popping off the stack and returning their results.

What is a Recursive Algorithm?

A recursive algorithm is an algorithm that uses recursion to solve a problem. Recursive algorithms typically have two parts:

  1. Base case: Which is a condition that stops the recursion.
  2. Recursive case: Which is a call to the function itself with a smaller version of the problem.

Types of Recursion

There are several different recursion types and terms. These include:

  • Direct recursion: This is typified by the factorial implementation where the methods call itself.
  • In-Direct recursion: This happens where one method, say method A, calls another method B, which then calls method A. This involves two or more methods that eventually create a circular call sequence.
  • Head recursion: The recursive call is made at the beginning of the method.
  • Tail recursion: The recursive call is the last statement.

When to Use Recursion?

Recursion is a powerful technique that can be used to solve a wide variety of problems. However, it is important to use recursion carefully, as it can lead to stack overflows if not used properly.

Recursion should be used when:

  • The problem can be broken down into smaller subproblems that can be solved recursively.
  • The base case is easy to identify.
  • The recursive calls are tail recursive.

Examples of Recursion

Here are some common examples of recursion:

Example 1: Factorial: The factorial of a number n is the product of all the integers from 1 to n. The factorial of n can be defined recursively as:

factorial(n) = n * factorial(n-1)

Example 2: Fibonacci sequence: The Fibonacci sequence is a sequence of numbers where each number is the sum of the two preceding numbers. The Fibonacci sequence can be defined recursively as:

fib(n) = fib(n-1) + fib(n-2)

Applications of Recursion Algorithms:

Here are some common applications of recursion:

  • Tree and Graph Traversal: Depth-first search (DFS) and breadth-first search (BFS)
  • Dynamic Programming: Solving optimization problems by breaking them into smaller subproblems
  • Divide-and-Conquer: Solving problems by dividing them into smaller parts, solving each part recursively, and combining the results
  • Backtracking: Exploring all possible solutions to a problem by recursively trying different options
  • Combinatorics: Counting or generating all possible combinations or permutations of a set

Learn Basics of Recursion Algorithms:

Recursion in Different Languages:

Easy Problems on Recursion

Medium Problems on Recursion

Hard Problems on Recursion

Practice Sets on Recursion

Quiz based on Recursion:



Previous Article
Next Article

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
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
Remove duplicates from a sorted linked list using recursion
Write a removeDuplicates() function which takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60. Algorithm: Traverse th
8 min read
Reverse a Doubly linked list using recursion
Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked List Algorithm: If list is empty, return Reverse head by swapping head->prev and head->next If prev = NULL it means that list is fully reversed. Else reverse(head->p
9 min read
Sum of natural numbers using recursion
Given a number n, find sum of first n natural numbers. To calculate the sum, we will use a recursive function recur_sum().Examples : Input : 3 Output : 6 Explanation : 1 + 2 + 3 = 6 Input : 5 Output : 15 Explanation : 1 + 2 + 3 + 4 + 5 = 15 Below is code to find the sum of natural numbers up to n using recursion : C/C++ Code // C++ program to find
3 min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Product of 2 Numbers using Recursion
Given two numbers x and y find the product using recursion. Examples : Input : x = 5, y = 2 Output : 10 Input : x = 100, y = 5 Output : 500 Method 1) If x is less than y, swap the two variables value 2) Recursively find y times the sum of x 3) If any of them become zero, return 0 C/C++ Code // C++ Program to find Product // of 2 Numbers using Recur
4 min read
Delete a linked list using recursion
Delete the given linked list using recursion Method: If head equal to NULL then linked list is empty, we simply return. Recursively delete linked list after head node. Delete head node. Implementation: C/C++ Code // C++ program to recursively delete a linked list #include <bits/stdc++.h> /* Link list node */ struct Node { int data; struct Nod
5 min read
Program for length of a string using recursion
Given a string calculate length of the string using recursion. Examples: Input : str = "abcd" Output :4 Input : str = "GEEKSFORGEEKS" Output :13 We have discussed 5 Different methods to find length of a string in C++ How to find length of a string without string.h and loop in C? Algorithm: recLen(str) { If str is NULL return 0 Else return 1 + recLe
3 min read
Print alternate nodes of a linked list using recursion
Given a linked list, print alternate nodes of this linked list. Examples : Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 Output : 1 -> 3 -> 5 -> 7 -> 9 Input : 10 -> 9 Output : 10 Recursive Approach : Initialize a static variable(say flag) If flag is odd print the node increase head and flag by 1,
6 min read
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965}; Output : 290 530 965 Tree represented is, 890 / \ 325 965 / \ 290 530 Input : preorder[] = { 3, 2, 4 }; Output : 2 4 In this post, a simple recursive sol
5 min read
Time Complexity Analysis | Tower Of Hanoi (Recursion)
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk ca
2 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
Preorder Traversal of N-ary Tree Without Recursion
Given an n-ary tree, print preorder traversal of it. Example : Preorder traversal of below tree is A B K N M J F D G E C H I L The idea is to use stack like iterative preorder traversal of binary tree. Create an empty stack to store nodes. Push the root node to the stack. Run a loop while the stack is not empty Pop the top node from stack. Print th
7 min read
Generating subarrays using recursion
Given an array, generate all the possible subarrays of the given array using recursion. Examples: Input : [1, 2, 3] Output : [1], [1, 2], [2], [1, 2, 3], [2, 3], [3] Input : [1, 2] Output : [1], [1, 2], [2] We have discussed iterative program to generate all subarrays. In this post, recursive is discussed. Approach: We use two pointers start and en
6 min read
Generating all possible Subsequences using Recursion including the empty one.
Given an array. The task is to generate and print all of the possible subsequences of the given array using recursion. Examples: Input : [1, 2, 3] Output : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3], [] Input : [1, 2] Output : [2], [1], [1, 2], [] Approach: For every element in the array, there are two choices, either to include it in the sub
5 min read
Product of 2 numbers using recursion | Set 2
Given two numbers N and M. The task is to find the product of the 2 numbers using recursion.Note: The numbers can be both positive or negative. Examples: Input : N = 5 , M = 3 Output : 15 Input : N = 5 , M = -3 Output : -15 Input : N = -5 , M = 3 Output : -15 Input : N = -5 , M = -3 Output:15 A recursive solution to the above problem for only posit
8 min read
Program to check if an array is palindrome or not using Recursion
Given an array. The task is to determine whether an array is a palindrome or not using recursion. Examples: Input: arr[] = {3, 6, 0, 6, 3}Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5}Output: Not Palindrome Approach: Base case: If array has only one element i.e. begin == end then return 1, also if begin>end which means the array is palindrome
4 min read
Difference between Recursion and Iteration
A program is called recursive when an entity calls itself. A program is called iterative when there is a loop (or repetition). Example: Program to find the factorial of a number C/C++ Code // C program to find factorial of given number #include <stdio.h> // ----- Recursion ----- // method to find factorial of given number int factorialUsingRe
8 min read
Delete nodes which have a greater value on right side using recursion
Given a singly linked list, remove all the nodes which have a greater value on the right side. Examples: a) The list 12->15->10->11->5->6->2->3->NULL should be changed to 15->11->6->3->NULL. Note that 12, 10, 5 and 2 have been deleted because there is a greater value on the right side. When we examine 12, we see
7 min read
Article Tags :
Practice Tags :