Skip to content

What is Recursion?

Foundations·7 min·Python code

Recursion solves a problem by having a function call itself on a smaller version of that problem. Every call moves toward a base case, and once the base case answers directly, the paused calls finish in reverse order.

Recursion Solves Smaller Copies of a Problem

Some problems are built from smaller copies of themselves. Sorting a stack of papers means sorting both halves and merging them, and counting files in a folder means counting files in the subfolders and adding them up.

Recursive functions mirror that structure. They handle one small step directly and hand the rest to another copy of themselves on a smaller input.

Every recursive function answers two questions. What smallest case can you solve immediately, without recursing? That is the base case.

How do you reduce a bigger case to a smaller one of the same kind and combine the result? That is the recursive case.

Get both right and the function works. Forget the base case and it calls itself forever.

How the Call Stack Handles Recursive Calls

When a function calls itself, the program pauses the caller instead of discarding it. One frame per active call sits on the call stack, holding that call's local variables and the line to return to.

factorial(4) calls factorial(3), which calls factorial(2), so four frames pile up before any finishes. factorial(1) returns 1 without recursing, then factorial(2) computes 2 × 1 and pops, and control flows back until factorial(4) returns 24.

That depth is extra space you pay even when the code looks compact. Python defaults to a limit of roughly 1000 frames, and passing it raises a RecursionError.

Recursion on Trees and Nested Data

Recursion fits data that is itself recursive. Any binary tree is either empty or a node with a left subtree and a right subtree, and subtrees are smaller trees.

That definition gives a base case (empty) and a recursive case (a node plus two subtrees), so traversal code matches the definition. Handle the empty case, recurse left, visit the node and recurse right.

Loops need an explicit stack managed by hand for the same job, while recursion lets the call stack do the bookkeeping. Depth-First Search uses the same pattern on graphs.

Watching calls expand down one branch and collapse back up makes the idea click.

Apply recursion on CodeStory's recursion practice problems.

Recursion Code Example in Python

pythonFactorial and in order tree traversal in Python. Both define a base case, then recurse on a smaller input.

def factorial(n):
    """Return n! using recursion. Assumes n >= 0."""
    # Base case: 0! and 1! are both 1: stop recursing.
    if n <= 1:
        return 1
    # Recursive case: n! = n * (n - 1)!
    return n * factorial(n - 1)


def inorder(node, visit):
    """Visit a binary tree's values in sorted (in-order) order."""
    if node is None:            # Base case: empty subtree.
        return
    inorder(node.left, visit)   # Recurse left,
    visit(node.value)           # process this node,
    inorder(node.right, visit)  # then recurse right.

Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App

Recursion Time and Space Complexity

TimeNumber of recursive calls times work per call. Factorial costs O(n) and a full tree traversal costs O(n) for n nodes
SpaceO(d) for recursion depth d, which is O(n) for factorial and O(h) for a tree of height h

Depth is O(log n) for a balanced tree and O(n) for a degenerate one. Naive recursion that solves overlapping subproblems again, like plain Fibonacci, explodes to O(2ⁿ) unless you memoize.

Watch Recursion Step by Step

Seeing calls expand down one branch and collapse back up shows how the stack works. Follow either of these one step at a time.

When to Use Recursion

  • Traversing or building tree and graph structures, where every node has the same shape as the full structure, like depth first search, tree height and folder walks.
  • Divide and conquer algorithms that split a problem into smaller identical subproblems, like merge sort, quick sort and binary search.
  • Problems defined by a recurrence or by exploring choices with undo, like factorial, permutations, subsets and N-Queens.
  • Cases where recursion looks far clearer than a loop, like flattening arbitrarily nested data.

Mistakes to Avoid

  • Missing or unreachable base cases, or recursive calls that do not shrink the input, which cause infinite recursion and stack overflow.
  • Solving the same subproblem again and again. Naive Fibonacci costs O(2ⁿ), so add memoization or move to dynamic programming when subproblems overlap.
  • Ignoring stack depth limits. Deep linear recursion crashes on large inputs, so rewrite it as a loop or with an explicit stack when depth can grow without bound.

Recursion FAQs

Is recursion hard to learn?

It feels hard at first because you trust the function to solve the smaller case before you finish writing it. Learn the two part pattern, a base case plus a recursive case that shrinks the input, and most recursive functions share that shape. Tracing small examples by hand makes it click.

When should I use recursion instead of a loop?

Use recursion when data or problems are naturally recursive, like trees, graphs, nested structures and divide and conquer. Use a loop for plain linear iteration or when depth could overflow the stack. Both are equally capable, so choose the one that looks clearer and stays safe.

What is the time complexity of a recursive function?

Multiply the number of recursive calls by the work per call. Factorial costs O(n), balanced divide and conquer costs O(n) or O(n log n), and naive Fibonacci blows up to O(2ⁿ). Draw the recursion tree or solve a recurrence, for example with the Master Theorem, to find it.

What causes a stack overflow in recursion?

Every active call stays on the call stack until it returns, so recursion that goes too deep or never reaches its base case exhausts the stack. Make sure the base case is always reached, convert to iteration or raise the stack limit.

What is a base case in recursion?

Base cases are the smallest inputs a function answers directly without calling itself. They stop the recursion and let paused calls return.

What is the difference between recursion and iteration?

Recursion repeats work by calling the function on a smaller input and uses call stack space. Iteration repeats work with a loop and needs only the variables you keep. Any recursive function can become a loop, though trees and nested data look clearer with recursion.

How do I practise recursion on CodeStory?

Watch Fibonacci and tree traversals in the visualisers, then open CodeStory's recursion practice problems and trace every call.

Related Guides

Guides are step one. In a CodeStory batch you code the base case yourself, then trace every call in a scored mock round.

Talk to a Mentor

Stuck on Recursion? Get a Free Callback

Tell CodeStory which call confuses you, and a mentor shapes your next steps.

  1. 1CodeStory finds your starting point, from your first base case to interview ready.
  2. 2CodeStory explains online and campus batches, with timings for your mornings or evenings.
  3. 3You decide. No pressure, no payment on the call.

Get a Free Callback

I am a
I want to learn

CodeStory dials your number only for this callback.