What is recursion?
A programming technique where a function calls itself to solve a problem by breaking it into smaller versions of the same problem. Like solving a puzzle by solving smaller parts of the same puzzle.
What is a base condition in recursion?
Factorial Example
The stopping condition that prevents infinite recursion. It’s the simplest case that can be solved directly without further recursive calls.
Example: In factorial(n), base case is when n=0 or n=1.
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
return n * factorial(n-1) #recursive case
When is it appropriate to use recursion?
Use recursion when:
Examples:
* Tree traversal
* Fibonacci sequence
* Directory traversal
* Divide and conquer algorithms