Recursion
Recursion
Srivaths P
Profile: https://sriv.bio.link/
Goal:
• Understand recursion
• Understand and create recursive trees
• Understand applications of recursion
• Assess time complexity of recursive algorithms
Recap on Functions
• A function is a block of code which runs the
code inside with the parameters it is given.
The above function will find the sum from 0 to the given
parameter.
Recursive Tree
A recursive tree is similar to a “mind map” of the
function call. Each node/vertex is the function call.
Value inside the node is the parameter.
• Brute-force
• Backtracking
• Dynamic Programming
• Graph/Tree Problems
• Etc.
Quiz 1
1. Write a recursive function to calculate the
factorial of a number.
void recurse(int n) {
void recurse(int n) { if (n == 0)
if (n == 0) return;
return; recurse(n/2);
recurse(n/2); recurse(n/2);
} }
Quiz 2
1. Print all N numbers such that each value can be from 0 to
K.
2. Given N coins, print all the values you can make with some
combination of coins and sum <= given K.
void f(int n) {
if (n == 0) return;
3. What is the time complexity of: if (n % 2 == 0)
f(n/2);
if (n % 2 == 1) f(n-
1);
}
Resources
• https://bit.ly/39lNlVT (very detailed explanation)
• https://codeforces.com/blog/entry/92031 (advanced)