Lesson 15
Recursion
Recursion is a technique where a function calls itself to solve a problem by breaking it down into smaller subproblems of the same type.
- What is Recursion?
- Base Case & Recursive Case
- How Recursion Works
- Call Stack
- Examples
- When to Use Recursion?
- 1Function Call
The function is called with some input.
fact(4) - 2Recursive Call
The function calls itself with a smaller input.
fact(3) - 3Base Case
The function reaches the base case and returns.
fact(1) = 1 - 4Backtracking
The control returns back, computing the result.
Returns 24
Factorial of n (n!) = n × (n-1) × (n-2) × ... × 1. Base case: 0! = 1
JavaScript
Output
Your output will appear here...
Growing
fact(4)4 × fact(3)
fact(3)3 × fact(2)
fact(2)2 × fact(1)
fact(1)Base Case → 1
Unwinding
Stack grows on calls and shrinks when the base case is reached.
- Every recursive solution must have a base case.
- Each recursive call moves closer to the base case.
- Recursion uses extra memory (call stack).
- Not all problems benefit from recursion.
Always define a base case, otherwise the recursion will run infinitely!
5!
Factorial
n! = n × (n-1) × ... × 1
∿
Fibonacci
Find nth Fibonacci number
Tree Traversal
Preorder, Inorder, Postorder
Backtracking
Solve puzzles & combinations
