Danielle B. answered 4d
Computer Science Tutor Specializing in Python and Data Science
Recursion takes place when a function calls itself to solve a problem by breaking it into smaller, simpler versions of the same problem. A recursive function needs:
- A base case:
- this is the simplest version of the problem and can be solved without another recursive call.
- A recursive case:
- the function calls itself with simpler input, moving toward the base case.
Recursion is common with tree and graph traversal, divide and conquer algorithms, backtracking problems (ex. maze, Sudoku), parsing and math sequences (ex. Fibonacci numbers, Tower of Hanoi).
The tradeoff with using recursion: it can make your code cleaner and more readable but this comes with a cost. Each function call adds to the call stack, so deep recursion runs the risk of causing a stack overflow.