📌 Tail Recursion & Removing Recursion (Iteration vs Recursion in Problem Solving)
1️⃣ What is Tail Recursion?
Tail Recursion is a type of recursion where the recursive call is the last operation before returning the final result.
💡 Advantage: It can be optimized by compilers to use constant stack space (Tail Call Optimization - TCO).
Example: Tail Recursive Factorial
🔹 Why Tail Recursive?
👉 The recursive call is the last operation before returning.
👉 No extra computation happens after the function call.
2️⃣ Removing Recursion (Converting to Iteration)
Recursion can lead to stack overflow for deep recursion. Iteration avoids this by using loops instead of function calls.
Example: Converting Recursive Factorial to Iterative
🔹 Advantages of Iteration:
✅ Saves memory (no recursive calls).
✅ Faster execution (no overhead of function calls).
3️⃣ Example: Binary Search (Recursion vs Iteration)
Binary search is a classic example where recursion and iteration can be used interchangeably.
Recursive Binary Search
Iterative Binary Search
🔹 Which is better?
Criteria | Recursive Binary Search | Iterative Binary Search |
---|---|---|
Memory Usage | Higher (Function calls in stack) | Lower (No extra memory needed) |
Performance | Slightly slower (Function call overhead) | Faster (No recursion overhead) |
Readability | More intuitive | Slightly complex |
Tail Recursion? | No | Not applicable |
4️⃣ When to Use Recursion vs Iteration?
✅ Use Recursion When:
✔ The problem has a natural recursive structure (e.g., Trees, DFS, Fibonacci).
✔ Readability is more important than performance.
✅ Use Iteration When:
✔ Performance and memory efficiency are critical.
✔ The recursion depth can be too large, leading to a stack overflow.
No comments:
Post a Comment