Recursion in C++: Structure With Examples
Learn how functions can call themselves to solve complex problems elegantly. Master the base case, recursive case, and call stack with practical examples. This chapter covers recursion in C++ from first steps to backtracking.
- What recursion is and how it works in C++
- The concepts of base case and recursive case
- How to write recursive functions for common problems
- How the call stack works during recursion
- Common pitfalls and when to use recursion
- Tree traversals, DFS and backtracking
1What is recursion?
Recursion is a programming technique where a function calls itself to solve a smaller version of the original problem.
In simpler terms: a function solves a problem by solving a smaller part of it repeatedly until it reaches a stopping condition.
2Structure of a recursive function
Every recursive function must have two essential parts:
- Base Case: A condition that ends the recursion (stops the function from calling itself forever)
- Recursive Case: The part where the function calls itself with a smaller or simpler version of the problem
General pattern:
returnType functionName(parameters) { if (base_case_condition) return base_value; else return functionName(smaller_problem); }
3Example 1: Factorial (n!)
The factorial of a number n is defined as: n! = n × (n-1) × (n-2) × ... × 1, and 0! = 1 (base case).
int factorial(int n) { if (n == 0) return 1; // base case else return n * factorial(n - 1); // recursive case }
Usage:
int main() { int n = 5; cout << "Factorial of " << n << " is " << factorial(n); return 0; }
4How recursion works: the call stack
When you call a recursive function, each call is placed on the call stack. Once the base case is reached, the calls start returning one by one, in reverse order.
For factorial(3):
-> 3 * factorial(2)
-> 2 * factorial(1)
-> 1 * factorial(0)
-> 1 (base case)
<- returns 1 * 1 = 1
<- returns 2 * 1 = 2
<- returns 3 * 2 = 6
5Example 2: Fibonacci sequence
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, ...
fib(0) = 0fib(1) = 1fib(n) = fib(n-1) + fib(n-2)for n > 1
int fib(int n) { if (n == 0) return 0; if (n == 1) return 1; return fib(n - 1) + fib(n - 2); }
cout << fib(7) << endl;
fib(5) calls fib(3) multiple times. We will discuss optimizations like memoization in later chapters.
6Example 3: Sum of digits
This function recursively calculates the sum of digits of a number. For n = 123, it returns 1 + 2 + 3 = 6.
int sumOfDigits(int n) { if (n == 0) return 0; return n % 10 + sumOfDigits(n / 10); }
cout << sumOfDigits(123) << endl;
7Example 4: Power function
Compute a^b (a raised to the power b) using recursion.
int power(int a, int b) { if (b == 0) return 1; return a * power(a, b - 1); }
cout << power(2, 5) << endl;
8Example 5: Tower of Hanoi
The Tower of Hanoi is a classic recursion problem. Move n disks from rod A to rod C using rod B as auxiliary.
void hanoi(int n, char source, char helper, char destination) { if (n == 1) { cout << "Move disk 1 from " << source << " to " << destination << endl; return; } hanoi(n - 1, source, destination, helper); cout << "Move disk " << n << " from " << source << " to " << destination << endl; hanoi(n - 1, helper, source, destination); }
hanoi(3, 'A', 'B', 'C');
9When should you use recursion?
- The problem can be broken into smaller, similar subproblems
- You can define a clear base case
- The problem involves tree traversal, divide-and-conquer, backtracking, or combinatorics
- The recursive solution is more elegant and readable than the iterative one
- The iterative solution is simpler and more efficient
- The recursion depth could be very large (risk of stack overflow)
- Performance is critical and recursion adds unnecessary overhead
10Common mistakes to avoid
11Recursion in real programs: trees and graphs
Real-Life Applications of Recursion
- Mathematical Functions: factorial, Fibonacci, GCD
- Data Structures: linked lists, trees, graphs
- File System Traversals: searching directories
- Dynamic Programming: memoization & optimization
- Backtracking: pathfinding, puzzles, permutations
Recursive Traversal in Data Structures
Let’s explore how recursion makes it easy to traverse complex data structures.
1. Binary Tree Traversals (Inorder, Preorder, Postorder)
Inorder (Left, Root, Right)
void inorder(TreeNode* root) {
if (!root) return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
Preorder and Postorder (just change order)
2. Depth-First Search (DFS) in Graph
void dfs(int node, vector<bool>& visited, vector<vector<int>>& graph) {
visited[node] = true;
cout << node << " ";
for (int neighbor : graph[node]) {
if (!visited[neighbor])
dfs(neighbor, visited, graph);
}
}
Example:
Graph:
0 → 1, 2
1 → 3
2 → 4
DFS output from 0: 0 1 3 2 4
12Backtracking
Backtracking: Solving Problems Recursively with Pruning
Backtracking is a method of exploring all possibilities and backtracking when an invalid path is encountered.
Template:
void backtrack(args...) {
if (solution found) {
process();
return;
}
for (choices...) {
makeChoice();
backtrack(next args...);
undoChoice(); // backtrack
}
}
Backtracking Examples
1. Generating All Subsets
void generateSubsets(vector<int>& nums, int index, vector<int>& current, vector<vector<int>>& result) {
if (index == nums.size()) {
result.push_back(current);
return;
}
// Exclude
generateSubsets(nums, index + 1, current, result);
// Include
current.push_back(nums[index]);
generateSubsets(nums, index + 1, current, result);
current.pop_back(); // Backtrack
}
2. N-Queens Problem
Place N queens on an N×N board such that no two queens attack each other.
bool isSafe(vector<string>& board, int row, int col, int n) {
for (int i = 0; i < row; i++) {
if (board[i][col] == 'Q') return false;
if (col - row + i >= 0 && board[i][col - row + i] == 'Q') return false;
if (col + row - i < n && board[i][col + row - i] == 'Q') return false;
}
return true;
}
void solveNQueens(int row, vector<string>& board, vector<vector<string>>& result, int n) {
if (row == n) {
result.push_back(board);
return;
}
for (int col = 0; col < n; col++) {
if (isSafe(board, row, col, n)) {
board[row][col] = 'Q';
solveNQueens(row + 1, board, result, n);
board[row][col] = '.'; // Backtrack
}
}
}
3. Rat in a Maze
Move from top-left to bottom-right of a grid with only right and down moves, avoiding blocked cells.
void findPaths(vector<vector<int>>& maze, int x, int y, int n, string path, vector<string>& result) {
if (x < 0 || y < 0 || x >= n || y >= n || maze[x][y] == 0)
return;
if (x == n - 1 && y == n - 1) {
result.push_back(path);
return;
}
maze[x][y] = 0; // Mark as visited
findPaths(maze, x + 1, y, n, path + "D", result);
findPaths(maze, x - 1, y, n, path + "U", result);
findPaths(maze, x, y + 1, n, path + "R", result);
findPaths(maze, x, y - 1, n, path + "L", result);
maze[x][y] = 1; // Backtrack
}
13Recursion vs iteration
When Not to Use Recursion
- When you’re facing tight memory limits (deep recursion = stack overflow).
- When a simple loop would do the job faster (e.g., iterating through an array).
Comparison: Recursion vs Iteration
| Aspect | Recursion | Iteration |
|---|---|---|
| Code Simplicity | More elegant, cleaner | May be verbose |
| Memory Usage | Uses stack, can overflow | Memory efficient |
| Performance | Slightly slower due to call overhead | Usually faster |
| Use Case | Tree/Graph problems, backtracking | Linear traversals, simple loops |
14Mini exercises
- Write a recursive function to calculate the sum of the first n natural numbers.
- Create a recursive function to check if a string is a palindrome.
- Implement
gcd(a, b)using recursion (Hint: use Euclid's algorithm:gcd(a, b) = gcd(b, a % b)). - Use recursion to reverse an array in place.
Hint: For the palindrome check, compare the first and last characters, then recurse on the substring between them.