Recursion
A recursive function solves a problem by calling itself on a smaller version of the same problem.
Easy
Every recursive function needs a base case (when to stop) and a recursive case that moves toward it.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1)
Each call uses a new stack frame, so very deep recursion can cause a stack overflow — a real risk on microcontrollers with only a few KB of RAM. Many recursive algorithms can be rewritten as loops.
Recursion shines for naturally recursive data: trees, divide-and-conquer sorting (merge sort, quick sort) and backtracking.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.