Home › Theme B › B2 › B2.4 › B2.4.4

B2.4.4 What recursion is

HL onlyCommand term: Explain

1. A function that calls itself

Step through factorial(4). Each call waits on the call stack for a smaller version of the same problem, until the base case stops the chain. Then the answers flow back.

2. Recursion tree explorer

Every call is a node; its children are the calls it makes. Watch the calls happen in order, and count them. Some recursive designs are efficient; others repeat the same work again and again.

Function:   n = 5

3. Quicksort: recursion that sorts

Quicksort picks a pivot, partitions the list into smaller and larger items, then recursively sorts each part. The brackets below the bars show the sub-lists still waiting on the call stack.

Data:   n = 12

4. Recursive art: fractals

A fractal is made of smaller copies of itself, so the drawing code calls itself on each smaller copy. Increase the depth and watch the number of calls grow.

Fractal: TreeSierpinski triangle   depth = 5

5. Traversing a binary tree

A binary search tree of titles. Each node's subtrees are smaller trees, so traversal is naturally recursive: visit the left subtree, the node, then the right subtree. (Trees in depth: B4, HL.)

Order: In-orderPre-orderPost-order  
Press Traverse.

6. Flip-card deck

Click to flip. Say the answer before you flip.

7. Recursion or iteration?

Is recursion a natural fit, or is a loop the better tool? Streaks of 3+ score double.

Round 0/10Score 0Streak 0Best 0
Press start!

8. 45-second speed round: what does it return?

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 4, task 4 (HL). A real library is nested: the library holds sections, sections hold shelves, shelves hold books, and some sections hold sub-sections. A loop cannot easily handle "any depth"; recursion can. Implement quicksort for the catalogue, and two recursive functions for the nested library.

Expected output

[4, 7, 7, 12, 33, 51, 90] [] [5] 10 2 3 0

Design notes (for your IA log)

Check my code

    Next (B2.4.5): construct and trace your own simple recursive algorithms: factorial, recursive binary search, and string reversal.

    Practical tasks

    Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    Task 1: Watch factorial recurse

    Write a recursive factorial(n, depth=0) that prints an indented line on the way in (factorial(3)) and on the way out (returns 6), so you can see the call stack grow and shrink. Identify the base case and the recursive case.

    Starter file (write your code where it says pass # your code here):

    File: b2_4_4_average.py
    def factorial(n, depth=0):
        pass  # your code here
    
    # ---- tests ----
    factorial(4)
    

    Expected output when your code is correct:

    factorial(4)
      factorial(3)
        factorial(2)
          factorial(1)
          returns 1
        returns 2
      returns 6
    returns 24
    Hint
    Base case: n <= 1 returns 1. Recursive case: n * factorial(n - 1).
    Model solution
    File: b2_4_4_average_solution.py
    def factorial(n, depth=0):
        print("  " * depth + f"factorial({n})")
        if n <= 1:
            result = 1
        else:
            result = n * factorial(n - 1, depth + 1)
        print("  " * depth + f"returns {result}")
        return result
    
    # ---- tests ----
    factorial(4)
    
    Moderate

    Task 2: Digit sum and fast power

    Write recursive digit_sum(n) (e.g. 4096 → 19) and power(x, n) that uses xn = (xn/2)² for even n and x · xn−1 for odd n. Count how many calls power(2, 1000) makes.

    Starter file (write your code where it says pass # your code here):

    File: b2_4_4_moderate.py
    calls = 0
    
    def digit_sum(n):
        pass  # your code here
    
    def power(x, n):
        pass  # your code here
    
    # ---- tests ----
    print(digit_sum(4096), digit_sum(7))
    print(power(3, 5), power(2, 10))
    calls = 0
    print(power(2, 1000) == 2 ** 1000, calls)
    

    Expected output when your code is correct:

    19 7
    243 1024
    True 16
    Hint
    Compute the half power once and store it; calling it twice would destroy the speed-up.
    Model solution
    File: b2_4_4_moderate_solution.py
    calls = 0
    
    def digit_sum(n):
        if n < 10:
            return n
        return n % 10 + digit_sum(n // 10)
    
    def power(x, n):
        global calls
        calls += 1
        if n == 0:
            return 1
        if n % 2 == 0:
            half = power(x, n // 2)
            return half * half
        return x * power(x, n - 1)
    
    # ---- tests ----
    print(digit_sum(4096), digit_sum(7))
    print(power(3, 5), power(2, 10))
    calls = 0
    print(power(2, 1000) == 2 ** 1000, calls)
    
    Challenging

    Task 3: Flatten a nested list

    A reading list contains books and sub-lists of books, nested to any depth. Write recursive flatten(items) that returns all books in one flat list, and depth(items) that returns the deepest nesting level (a flat list has depth 1, an empty list depth 1).

    Starter file (write your code where it says pass # your code here):

    File: b2_4_4_challenging.py
    def flatten(items):
        pass  # your code here
    
    def depth(items):
        pass  # your code here
    
    # ---- tests ----
    reading = ["Dune", ["Emma", ["Holes", "Kim"]], [], ["Matilda"]]
    print(flatten(reading))
    print(depth(reading), depth([]), depth([1, 2]), depth([[[[]]]]))
    

    Expected output when your code is correct:

    ['Dune', 'Emma', 'Holes', 'Kim', 'Matilda']
    3 1 1 4
    Hint
    If an item is a list, recurse into it; otherwise it is a book.
    Model solution
    File: b2_4_4_challenging_solution.py
    def flatten(items):
        out = []
        for x in items:
            if isinstance(x, list):
                out.extend(flatten(x))
            else:
                out.append(x)
        return out
    
    def depth(items):
        deepest = 0
        for x in items:
            if isinstance(x, list):
                deepest = max(deepest, depth(x))
        return 1 + deepest
    
    # ---- tests ----
    reading = ["Dune", ["Emma", ["Holes", "Kim"]], [], ["Matilda"]]
    print(flatten(reading))
    print(depth(reading), depth([]), depth([1, 2]), depth([[[[]]]]))
    

    Learning objectives

    By the end of this page you should be able to:

    1. Explain recursion: a function that solves a problem by calling itself on a smaller version of it, with a base case and a recursive case.
    2. Explain how the call stack makes recursion work, and why recursion uses memory that grows with its depth.
    3. Describe how quicksort uses recursion (pivot, partition, sort each part) and state its time complexity.
    4. Evaluate the advantages and limitations of recursion, including complexity and memory usage.
    5. Identify situations that suit recursion, such as fractal images, traversing binary trees and sorting algorithms.

    What is recursion?

    A recursive function solves a problem by calling itself on a smaller instance of the same problem. Every correct recursive function has:

    • a base case: a simple version answered directly, without another call, which stops the recursion;
    • a recursive case: the function calls itself with an input that moves closer to the base case.
    def factorial(n):
        if n <= 1:                       # base case
            return 1
        return n * factorial(n - 1)      # recursive case: a smaller problem

    Without a reachable base case the calls never stop, and the program crashes with a stack overflow (Python: RecursionError: maximum recursion depth exceeded, usually after about 1,000 calls).

    The call stack

    Each call pushes a stack frame holding its parameters, local variables and return point (B2.2.3, B2.3.4). Recursive calls wind the stack up until the base case; then each call returns its result to the one below and its frame is popped, as the stack unwinds. A recursion of depth d therefore needs d frames at the same time: O(d) memory.

    Quicksort

    1. If the list has 0 or 1 items, it is already sorted (base case).
    2. Choose a pivot (here, the last item).
    3. Partition: move items smaller than the pivot to its left and larger ones to its right. The pivot is now in its final place.
    4. Recursively quicksort the left part and the right part.

    Each level of recursion does about n comparisons in total. With good pivots the list halves each time, so there are about log₂ n levels: O(n log n) on average, and O(log n) stack space. With bad pivots (already sorted data with the last item as pivot) each partition removes only one item: n levels, O(n²) time and O(n) stack depth. Choosing a random or median-of-three pivot makes this rare.

    Advantages and limitations

    AdvantagesLimitations
    Short, elegant code that mirrors the problem's definitionEach call has overhead (creating a frame), so it is often slower than a loop
    A natural fit for self-similar structures: trees, nested folders, fractalsMemory grows with depth; deep recursion overflows the stack
    Divide-and-conquer algorithms (quicksort, merge sort) are easy to expressHarder to trace and debug; a missing or wrong base case is easy to make
    Removes the need to manage an explicit stack yourselfNaive designs can repeat work: naive Fibonacci makes O(2ⁿ) calls

    When to use it

    Use recursion when a problem naturally breaks into smaller, similar subproblems and the depth is modest: fractal images, traversing binary trees, searching nested structures, divide-and-conquer sorting. Use a loop for simple repetition, long linear chains (summing a million numbers), or when memory is tight.

    Use the 中文 button at the top to show or hide the Chinese terms.

    Term中文Meaning

    Choose an answer. You get instant feedback.

    Score: 0 /

    Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

    1. Define recursion, and identify the base case and the recursive case in the function below. [3]

    def count_down(n):
        if n == 0:
            print("Go!")
        else:
            print(n)
            count_down(n - 1)
    Recursion is when a function calls itself to solve a smaller instance of the same problem [1]; base case: if n == 0: print("Go!"), which stops the recursion [1]; recursive case: count_down(n - 1), which moves n towards 0 [1].

    2. State the value returned by mystery(4), showing your working. [3]

    def mystery(n):
        if n == 1:
            return 2
        return 3 * mystery(n - 1) - 1
    mystery(1) = 2 [1]; mystery(2) = 3 × 2 - 1 = 5, mystery(3) = 3 × 5 - 1 = 14 [1]; mystery(4) = 3 × 14 - 1 = 41 [1].

    3. Explain how the call stack is used when factorial(3) is executed. [3]

    Each call pushes a new frame storing its own n and return address: factorial(3), factorial(2), factorial(1) [1]; factorial(1) reaches the base case and returns 1, and its frame is popped [1]; each waiting call then completes using the returned value (2 × 1 = 2, then 3 × 2 = 6) and is popped in turn, until 6 is returned [1].

    4. Describe how quicksort sorts a list. [4]

    A pivot element is chosen [1]; the list is partitioned so that items less than the pivot are placed before it and greater items after it, leaving the pivot in its final position [1]; quicksort is then called recursively on each of the two sublists [1]; the recursion stops when a sublist has zero or one element (base case) [1].

    5. Outline two limitations of using recursion. [4]

    Award [1] for each limitation and [1] for its outline, twice: memory usage, as every active call needs its own stack frame, so deep recursion uses O(depth) memory and can cause a stack overflow; overhead of function calls makes it slower than an equivalent loop; harder to trace / debug; inefficient designs can repeat calculations (naive Fibonacci is exponential).

    6. Explain why recursion is well suited to traversing a binary tree. [3]

    Each node's left and right children are themselves the roots of smaller binary trees / the structure is self-similar [1]; so traversal can be expressed as: traverse the left subtree, process the node, traverse the right subtree [1]; with an empty subtree as the base case; the call stack automatically remembers the path back up the tree, which an iterative version would have to manage explicitly [1].