int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
int main() {
cout << factorial(4) << endl;
}
factorial(0) = 1
factorial(n) = n * factorial(n-1)
n-1
if (base case)
solve the problem
else
reduce the problem
call the function again
n
disksNULL
or not
next
elementExample: computing the length of a linked list
Given a list of 0 -> 1 -> 2 -> 3 -> NULL
, trace the following:
void print(Node *head) {
while (head) {
cout << head->data << endl;
head = head->next;
}
}
void print(Node *head) {
if (head) {
cout << head->data << endl;
print(head->next);
}
}
Given a list of 0 -> 1 -> 2 -> 3 -> NULL
, trace the following:
void print(Node *head) {
if (head) {
print(head->next);
cout << head->data << endl;
}
}
There are scenarios where recursion is easier to read and implement
However, recursion comes at a cost:
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
The recursive solution just created n
stack frames complete with n
function return addresses and temporary variable allocations!
n
return
g++ may optimize other forms of recursion, but it's not guaranteed
Back to the linked list deletion example:
void clear_list(Node *head) {
if (head) {
clear_list(head->next);
delete head;
}
}
Can any recursive function be implemented iteratively?
Trace the following code and write the result:
int mystery(int n) {
if (n < 2)
return n;
else
return mystery(n-1) + mystery(n-2);
}
int main() {
cout << mystery(4) << endl;
}
bool in_array(int *arr, int size, int value) {
for (int i = 0; i < size; i++) {
if (arr[i] == value)
return true;
}
return false;
}
## The Towers of Hanoi: Recursive solution * Base case: one disk to move - Move it to the destination peg * Recursive case: `n` disks to move - Move the `n-1` disks from the source peg to the spare peg - Move the remaining disk to the destination peg - Move the `n-1` disks from the spare peg to the destination peg