Concepts 🚀 Project 🧮 Labs
📚 Learn / Algorithms & Data Structures / Recursion

Recursion

A function that calls itself. Needs a base case to terminate.

Code example

def factorial(n):
    if n <= 1:           # base case
        return 1
    return n * factorial(n - 1)  # recursive case

factorial(5)  # 120

How it works

Recursion is when a function calls itself. Every recursive function needs (1) a base case that returns without recursing, (2) a recursive case that calls itself with a smaller input. Without a base case, you get infinite recursion → stack overflow. Recursion is natural for tree-structured data (file systems, JSON, ASTs) and divide-and-conquer algorithms (merge sort, binary search). Python's default recursion limit is 1000 — deep recursion needs to be rewritten iteratively or you'll hit RecursionError.

🔍 Where this is used in OpenBenchML Used implicitly in JSON serialisation, ORM relationship walking, and template rendering.