Sub topic 18
Recursion Patterns: Tail, Tree, and Linked Structures
This chapter assumes you can trace a simple recursive function, know that each call gets its own stack frame, and can build a singly linked list with struct and malloc. Here we sort recursive functions into three recurring shapes. Each shape tells you how many calls to expect, how deep the stack gets, and in what order the output appears.
Three Shapes of Recursion
| Shape | Calls made per invocation | Typical stack depth | Example |
|---|---|---|---|
| Tail recursion | One, and it is the last action | n | `gcd` |
| Linear (non-tail) recursion | One, with work left after it returns | n | `print_rev` |
| Tree recursion | Two or more | Height of the call tree | `fib`, `hanoi` |
Ask two questions of any recursive function. How many recursive calls does one invocation make? Is there work after the call returns? The first question gives the running time. The second gives the order of side effects.
Tail Recursion
A call is a tail call if the function returns its result directly, with nothing left to do afterward. The Euclidean algorithm has this form:
#include <stdio.h>
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int main(void) {
printf("%d\n", gcd(48, 18));
return 0;
}This prints 6. The call chain is gcd(48,18), gcd(18,12), gcd(12,6), gcd(6,0). Each frame only waits to pass the result up unchanged.
Many functions are not tail recursive at first. n * fact(n-1) has a multiplication left over after the call. You can often fix this with an accumulator, an extra parameter that carries the partial result:
#include <stdio.h>
long sum_to(int n, long acc) {
if (n == 0) {
return acc;
}
return sum_to(n - 1, acc + n);
}
int main(void) {
printf("%ld\n", sum_to(4, 0));
return 0;
}This prints 10. The result is built on the way down, so nothing remains to do on the way back.
A compiler may reuse one frame for every tail call, which turns the recursion into a loop. The C standard does not require this. With optimization on, GCC and Clang usually do it. At -O0 they usually do not. For GATE, treat the stack depth of a tail-recursive function as O(n) unless the question says the compiler optimizes tail calls.
Linear Recursion and Order of Output
When the recursive call comes before a statement, that statement runs on the way back out. This reverses the order of work compared with a statement placed before the call.
#include <stdio.h>
void down_up(int n) {
if (n == 0) {
return;
}
printf("%d ", n);
down_up(n - 1);
printf("%d ", n);
}
int main(void) {
down_up(3);
printf("\n");
return 0;
}This prints 3 2 1 1 2 3. A statement before the call runs in descending order. A statement after it runs in ascending order, because the frames unwind last-in, first-out.
Tree Recursion
When a function calls itself two or more times, the calls form a tree. The number of calls can grow exponentially.
#include <stdio.h>
int calls = 0;
int fib(int n) {
calls++;
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
int main(void) {
int r = fib(5);
printf("%d %d\n", r, calls);
return 0;
}This prints 5 15. The result is read into r first, so the value of calls is well defined when it is printed. Writing printf("%d %d", fib(5), calls) would be a bug, because the order in which arguments are evaluated is unspecified.
The call tree for fib(4) has 9 nodes:
The recurrence for the number of calls is T(n) = T(n-1) + T(n-2) + 1. Its solution grows as about 1.618^n, which is exponential. The stack depth is only n, because the stack holds one root-to-leaf path at a time, not the whole tree. This difference between time and space is a common GATE question.
Tower of Hanoi is tree recursion with a cleaner recurrence:
#include <stdio.h>
void hanoi(int n, char from, char to, char via) {
if (n == 0) {
return;
}
hanoi(n - 1, from, via, to);
printf("Move disk %d from %c to %c\n", n, from, to);
hanoi(n - 1, via, to, from);
}
int main(void) {
hanoi(2, 'A', 'C', 'B');
return 0;
}The output is three lines: disk 1 from A to B, disk 2 from A to C, disk 1 from B to C. The recurrence is T(n) = 2T(n-1) + 1 with T(0) = 0, which solves to 2^n - 1 moves. The stack depth is n.
Recursion on Linked Structures
A linked list is a recursive structure. A list is either empty (NULL) or a node followed by a smaller list. So the base case is NULL, and the recursive case handles h and then recurses on h->next.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *push(struct node *head, int v) {
struct node *n = malloc(sizeof *n);
if (n == NULL) {
return head;
}
n->data = v;
n->next = head;
return n;
}
void print_rev(const struct node *h) {
if (h == NULL) {
return;
}
print_rev(h->next);
printf("%d ", h->data);
}
void free_list(struct node *h) {
while (h != NULL) {
struct node *t = h->next;
free(h);
h = t;
}
}
int main(void) {
struct node *head = NULL;
for (int i = 1; i <= 3; i++) {
head = push(head, i);
}
print_rev(head);
printf("\n");
free_list(head);
return 0;
}Pushing 1, 2, 3 at the head builds the list 3, 2, 1. print_rev prints after the recursive call, so it prints 1 2 3. Printing before the call would give 3 2 1.
Two points matter for this pattern:
- The check
h == NULLmust come before any use ofh->nextorh->data. DereferencingNULLis undefined behavior. - Recursion depth equals the list length. A list of a million nodes can overflow the stack in a recursive traversal, even though a loop handles it easily.
free_listis written as a loop for this reason.
Common Errors
- Missing or unreachable base case. If
ncan skip past 0, for example by stepping down by 2 from an odd number, the recursion never stops. The stack overflows, which is undefined behavior. - Assuming a tail call saves memory. Without compiler optimization, a tail-recursive function still uses O(n) stack.
- Mixing up time and stack depth. For
fib, time is exponential and depth is n. For Hanoi, time is 2^n and depth is n. - Wrong order of output. Put "before the call" and "after the call" labels on each
printfbefore you start tracing. - Ignoring evaluation order. Do not rely on a global counter being read in the same expression as the call that changes it.
Exercise
What does downup(2) print, using the downup function from this chapter? What is its maximum stack depth, counting each call to down_up including the one with n == 0?
Show answer
It prints "2 1 1 2". The calls are downup(2), downup(1), and down_up(0), so the maximum depth is 3 frames. The first printf runs on the way down (2, then 1). The second printf runs on the way back up (1, then 2).
Exercise
For fib as written above, the call count satisfies T(n) = T(n-1) + T(n-2) + 1 with T(0) = T(1) = 1. Compute T(4) and T(5). Then state the maximum stack depth of fib(n) in terms of n.
Show answer
T(2) = 1 + 1 + 1 = 3, T(3) = 3 + 1 + 1 = 5, T(4) = 5 + 3 + 1 = 9, and T(5) = 9 + 5 + 1 = 15. The maximum stack depth is about n, because the stack holds only the current root-to-leaf path of the call tree.
Exercise
Rewrite a recursive factorial so that it is tail recursive. Which parameter did you add, and what value should the first call pass for it?
Show answer
Add an accumulator: long fact(int n, long acc) { if (n <= 1) return acc; return fact(n - 1, acc * n); }. The first call is fact(n, 1), because 1 is the identity for multiplication.