Chapter 02 of 08

Recursion

Recursion
On this page

If you've been learning programming for a while, you've probably seen a function calling another function. But what if I tell you that a function can actually call itself?

Sounds strange, right?

At first, recursion feels like magic because the same function keeps calling itself again and again. Many beginners think, "Won't this run forever?" Well, it will if you don't know when to stop!

That's why recursion has two important parts:

  1. Keep breaking the problem into smaller problems.

  2. Stop when a specific condition is reached.

The infographic explains this beautifully using a magical tower with multiple floors. Let's understand every part of it.


What is Recursion?

The slide defines recursion as:

A recursive function calls itself until a stopping condition is reached.

That's the simplest definition you'll ever need.

Imagine you have to climb a five-floor tower.

Instead of jumping directly to the top, you climb:

  • Floor 1

  • Floor 2

  • Floor 3

  • Floor 4

  • Floor 5

Once you reach the top, you start coming back down one floor at a time.

Recursion works exactly like this.

It keeps going deeper into smaller versions of the same problem until it reaches the base case. Then it starts returning back, solving every previous function call.


The Three Main Ideas of Recursion

The infographic highlights three important points.

1. Function Calls Itself

This is what makes recursion unique.

Unlike normal functions, a recursive function invokes itself.

For example,

void print(int n){
    print(n-1);
}

Here the function is calling itself.

But this code is actually dangerous because there is no condition to stop it.

We'll see how to fix that later.


2. Smaller Problem

Recursion never tries to solve the entire problem at once.

Instead, it reduces the problem into a slightly smaller version.

For example,

Suppose you want to calculate:

5!

Instead of solving everything together, recursion thinks like this:

5! = 5 × 4!

Now,

4!

becomes another smaller problem.

Then,

4! = 4 × 3!

Again,

3!

becomes another smaller problem.

This continues until the smallest possible problem remains.


3. Same Logic Repeated

Notice something interesting.

Every recursive call does exactly the same thing.

It doesn't create new logic.

It simply repeats the same function on a smaller input.

That's why recursion is often called:

A problem that solves itself by solving a smaller version of itself.


Understanding the Recursive Flow

The center of the infographic shows the complete recursive flow.

It goes like this:

Problem
      ↓
Function()
      ↓
Smaller Problem
      ↓
Function()
      ↓
Smaller Problem
      ↓
Function()
      ↓
Base Case
      ↓
Return Values
      ↓
Final Answer

Notice the two arrows shown.

The blue arrow says:

Going Deeper (Calls)

This is when recursion keeps creating new function calls.

The green arrow says:

Coming Back (Returns)

Once the base case is reached, every function starts returning one by one.

This "go deeper, then come back" pattern is the heart of recursion.


The Tower Analogy (Base Case)

The magical tower in the infographic explains recursion perfectly.

Imagine Alex is climbing a tower.

He starts from Floor 1.

Then moves to:

  • Floor 2

  • Floor 3

  • Floor 4

Finally,

he reaches the Top Floor, where the wizard tells him:

Stop here. Start returning.

That top floor is called the Base Case.

Without it,

Alex would keep climbing forever.

Similarly,

without a base case,

a recursive function never stops calling itself.


What is the Base Case?

The infographic mentions three important things.

The base case:

  • Prevents infinite recursion.

  • Ends recursive calls.

  • Returns the first answer.

Think of it as the stopping point.

Every recursive function must have one.

Otherwise, your program eventually crashes with a Stack Overflow error.


Understanding the Factorial Example

The infographic uses one of the most common recursion examples—Factorial.

Remember,

5! = 5 × 4 × 3 × 2 × 1

Instead of multiplying everything together immediately, recursion breaks it down.

factorial(5)

= 5 × factorial(4)

= 5 × 4 × factorial(3)

= 5 × 4 × 3 × factorial(2)

= 5 × 4 × 3 × 2 × factorial(1)

Now the function reaches:

factorial(1)

This is the base case.

Instead of making another recursive call,

it simply returns:

1

Now everything starts returning.

factorial(2)

= 2 × 1

= 2

Then,

factorial(3)

= 3 × 2

= 6

Then,

factorial(4)

= 4 × 6

= 24

Finally,

factorial(5)

= 5 × 24

= 120

That's exactly why the infographic shows the answer:

120

The important thing to remember is that the multiplication doesn't happen while going deeper. It happens while coming back after reaching the base case.


Understanding the Code

The slide shows this C++ function:

int factorial(int n)
{
    if(n == 1)
        return 1;

    return n * factorial(n - 1);
}

Let's understand it line by line.

First,

if(n == 1)

This is the base case.

When the function reaches 1,

it stops making further recursive calls.

Then,

return n * factorial(n-1);

This line means:

Don't calculate everything yourself.

Ask a smaller version of the same function to solve the remaining problem.

Once that smaller answer comes back,

multiply it by n.

This is why recursion is so elegant.


Function Call Stack

The infographic also explains something extremely important—the Function Call Stack.

Every time a recursive function is called,

the computer stores information about that function in memory.

The stack shown contains:

factorial(5)

factorial(4)

factorial(3)

factorial(2)

factorial(1)

Each new function call is pushed onto the stack.

Once the base case is reached,

they start getting popped one by one.

This follows the LIFO (Last In, First Out) principle.

The last function added is the first one to finish.

This stack is managed automatically by the programming language.


Recursion vs Iteration

The infographic compares recursion with loops.

Recursion

Uses:

  • Function calls

  • Call Stack

  • Elegant code

Recursion often produces shorter and cleaner code for problems that naturally break into smaller subproblems.


Iteration

Uses:

  • Loops

  • Constant memory

  • Usually faster

Loops avoid the overhead of repeatedly creating function calls, so they are generally more memory-efficient and faster for simple repetitive tasks.

Both approaches solve problems, but the better choice depends on the problem itself.


Advantages of Recursion

The infographic highlights several benefits.

Elegant Code

Recursive solutions are often shorter and easier to read.


Easy Divide and Conquer

Large problems become much easier after dividing them into smaller ones.


Perfect for Tree Traversal

Almost every tree algorithm uses recursion because each subtree is simply a smaller version of the whole tree.


Natural Mathematical Solutions

Problems like:

  • Factorial

  • Fibonacci

  • Power

  • Greatest Common Divisor (GCD)

can be expressed very naturally using recursion.


Cleaner Logic

Sometimes recursive code is much easier to understand than deeply nested loops.


Real DSA Applications

Recursion is everywhere in Data Structures and Algorithms.

The infographic mentions several common applications.

Tree Traversal

Visiting every node in Binary Trees, BSTs, AVL Trees, and more.


Directory Traversal

Reading folders inside folders inside folders, just like your operating system explores file directories.


Although Binary Search can be implemented iteratively, the recursive version naturally divides the search space into smaller halves.


Divide and Conquer

Algorithms like Merge Sort and Quick Sort recursively divide a problem into smaller parts before combining the results.


Backtracking

Problems like Sudoku, N-Queens, Rat in a Maze, and Word Search rely heavily on recursion to explore possibilities.


Fibonacci

Each Fibonacci number depends on previous Fibonacci numbers, making it a classic recursive example (though the naive recursive solution is inefficient).


Depth First Search in graphs and trees naturally uses recursion to go as deep as possible before backtracking.


Factorial

A simple mathematical example that demonstrates how recursion works.


Disadvantages of Recursion

Recursion is powerful, but it isn't always the best choice.

The infographic lists a few drawbacks.

More Memory Usage

Every recursive call occupies space in the call stack.


Stack Overflow Risk

If recursion goes too deep or the base case is missing, the call stack keeps growing until the program crashes with a Stack Overflow error.


Slower Than Loops

Recursive calls introduce extra overhead because the system has to create and remove stack frames for every call.


Infinite Recursion

Forgetting or writing the wrong base case causes the function to call itself forever until memory runs out.


Time and Space Complexity of Recursion

The infographic reminds us that recursion has two types of complexity.

Time Complexity

Depends on:

  • How many recursive calls are made.

  • How much work each call performs.

For example, the factorial function makes n recursive calls, so its time complexity is O(n).

Space Complexity

Depends on the maximum depth of the recursive call stack.

For the factorial example, there are n active function calls before the base case is reached, so the space complexity is also O(n).

Not all recursive algorithms have the same complexity. Some, like Binary Search, use only O(log n) stack space because each call halves the problem size.


A Few Important Things to Know

Here are a few concepts that are important but aren't explicitly shown in the infographic:

  • Every recursive problem can usually be solved iteratively, although the iterative solution may be longer or less intuitive.

  • Tail recursion is a special form of recursion where the recursive call is the last operation. Some programming languages optimize it to reduce stack usage, but Java does not perform tail call optimization.

  • Recursive functions should always move toward the base case. If the problem size doesn't decrease with each call, the recursion will never terminate.

  • Memoization is often combined with recursion to avoid solving the same subproblem repeatedly, especially in Dynamic Programming problems like Fibonacci.


Conclusion

Recursion is one of the most important concepts in Data Structures and Algorithms because it teaches you how to solve large problems by repeatedly solving smaller versions of the same problem. The key idea is simple: keep breaking the problem into smaller parts, stop at the base case, and then let the answers return back through the call stack. Once you understand this flow, many advanced topics like trees, graphs, backtracking, divide-and-conquer algorithms, and dynamic programming become much easier to learn.


Quick Revision

Concept

Remember

Recursion

A function calls itself to solve a smaller version of the same problem.

Base Case

Stops recursion and begins returning answers.

Recursive Case

Breaks the problem into a smaller subproblem.

Call Stack

Stores every active recursive function call (LIFO).

Going Deeper

Recursive calls are pushed onto the stack.

Coming Back

Calls return one by one after reaching the base case.

Advantages

Elegant code, divide & conquer, tree traversal, backtracking.

Disadvantages

More memory, slower than loops, stack overflow risk if the base case is missing.

Factorial Example

5! = 5 × 4 × 3 × 2 × 1 = 120

Complexity

Time depends on recursive calls; space depends on recursion depth (call stack).