Opening Scenario

You inherit a service that walks nested org charts. Each manager has reports; each report may be a manager too. The original author wrote it recursively:

# Python
def count_reports(person):
    return 1 + sum(count_reports(r) for r in person.reports)

It worked fine on test data. In production, a legitimate org with 5,000 deeply nested contractors under one VP starts blowing up:

RecursionError: maximum recursion depth exceeded

You rewrite it with a loop and a stack — no more crash. But someone on review asks "was the recursion actually wrong, or was the data shape wrong?" Meanwhile a Java colleague says "that's why we use an explicit stack." And a C++ colleague shrugs: "same code in C++ would've just stack-overflowed and SIGSEGV'd. You'd prefer the Python exception."

What does recursion actually cost, and when is it the right tool?


Question Progression

Q1: What happens in memory when a function calls itself?

Question: count_reports calls count_reports, which calls count_reports. Where…

In the full tutorial

  • When to Reach for This

Glossary history

Click dotted jargon to save explanations here.