Data Structures18 min read

Recursion for Structures

Understand recursion as a tool for nested data, trees, and parsing. Learn base case, recursive step, and how to avoid infinite recursion.

David Miller
October 10, 2025
4.9k241

Recursion means a function calls itself.

It is useful for:

  • nested structures
  • trees
  • divide-and-conquer logic

The two rules

  1. Base case (stop condition)
  2. Recursive step (smaller problem)

Example: sum nested list

def deep_sum(data):
    total = 0
    for item in data:
        if isinstance(item, list):
            total += deep_sum(item)
        else:
            total += item
    return total

print(deep_sum([1, [2, 3], [4, [5]]]))  # 15

Graph: recursion idea

flowchart TD
  A[Problem] --> B[Smaller problem]
  B --> C[Smaller problem]
  C --> D[Base case]
  D --> E[Return up]

Remember

  • Always define a base case
  • Each call must reduce the problem
  • Recursion is common in tree/graph processing
#Python#Intermediate#Recursion