Sub topic 16
Recursion Patterns: Tail, Tree, and Linked Structures
Assume you know C functions, pointers, struct declarations, and the idea of a base case. Recursion is useful when a problem can be described using a smaller version of itself. The recursive call must move toward a base case.
Tail recursion
A function is tail-recursive when its recursive call is the final operation before returning. No work remains after that call.
#include <stdio.h>
#include <stdlib.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int fib(int n) {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
struct node {
int data;
struct node *next;
};
void print_list(const struct node *p) {
if (p == NULL) {
return;
}
printf("%d ", p->data);
print_list(p->next);
}
int main(void) {
struct node *a = malloc(sizeof *a);
struct node *b = malloc(sizeof *b);
struct node *c = malloc(sizeof *c);
if (a == NULL || b == NULL || c == NULL) {
free(a);
free(b);
free(c);
return 1;
}
a->data = 10;
b->data = 20;
c->data = 30;
a->next = b;
b->next = c;
c->next = NULL;
printf("gcd = %d\n", gcd(48, 18));
printf("fib = %d\n", fib(5));
print_list(a);
printf("\n");
free(c);
free(b);
free(a);
return 0;
}gcd is tail-recursive. Once it calls itself, it has no additional operation to perform. Tail recursion can use constant stack space if a compiler optimizes it, but C does not require that optimization. For GATE questions, count stack frames unless optimization is explicitly stated.
Tree recursion
A function has tree recursion when one call creates two or more recursive calls. Fibonacci recursion is a standard example:
fib(n) = fib(n - 1) + fib(n - 2)
The same values are computed repeatedly. Its time complexity is exponential, approximately O(2^n), while its maximum stack depth is O(n).
Recursion on linked structures
A linked list naturally supplies a smaller problem: the list beginning at p->next. The base case is a null pointer. The example prints each node before the recursive call, so it prints in forward order. Moving the printf statement after the call prints in reverse order.
Exercise
What is the maximum number of active recursive calls when print_list processes a list containing 4 nodes?
Show answer
Five function frames can exist: one for each of the 4 nodes and one final call whose argument is NULL.