Recursion
Recursion isn't technically an algorithm. It's more of a concept. It is a function that call itself inside of the function. It is really good for tasks that have repeated sub tasks to do.
Two problems of recursion is the risk of stack overflow and it is not memory efficient as our stacks need to hold and remember these function call.
Three things to remember when creating recursive function:
Establish Base Case / Stop Point
Establish Recursive Case
Create two returns for base and recursive case
Anything you can do with recursively can be done iteratively (loop)
Pros of recursion:
More readable
DRY principal
Cons of recursion:
Not memory efficient
The rule of thumb of when to use recursion is when you're working with data structures that you're not really sure how deep they are or where you don't know how many loops to go through. For example doing traversal in tree data structure.
Consider recursion every time you are using a tree or converting something into a tree.
1. Divided into a number of sub-problems that are smaller instances of the same problem
2. Each instance of the sub-problems is identical in nature
3. The solutions of each sub-problems can be combined to solve the problem at hand
Divide and conquer approach using recursion
Last updated