Intern
Mis on rekursioon?
sobes.tech AI
Vastus AI-lt
Recursion is the process where a function calls itself. In programming, a recursive function is one that calls itself directly or indirectly. To avoid an infinite loop, a recursive function must have a base case, at which point it stops calling itself.
Examples of use:
- Traversing data structures (e.g., trees).
- Solving problems that can be broken down into smaller subproblems of the same type (e.g., calculating factorial).
Example of calculating factorial using recursion:
def factorial(n):
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: factorial of n = n * factorial of (n-1)
else:
return n * factorial(n - 1)
# Example of use
result = factorial(5)
# result will be 120
Disadvantages of recursion:
- Can consume a lot of memory due to the call stack.
- May be less efficient compared to iterative solutions for some problems.
- Can lead to stack overflow in deep recursive calls.