- 2074 Bhadra · 1+3+4 marks
Tree recursion and TOH with n disks
Short answer
Tree recursion makes more than one recursive call per invocation, forming a call tree, as in Fibonacci and TOH. TOH algorithm: if n=1 move disk; else TOH(n-1,from,aux,to), move disk n, TOH(n-1,aux,to,from). For 3 disks the recursion tree has root TOH(3,A,C,B) and two TOH(2) subtrees; moves are printed in in-order, 7 calls.
What is tree recursion? Write an algorithm for TOH with n disks and generate a recursion tree of TOH problem with 3 disks.
Tree recursion
A recursive function that makes more than one recursive call in its body is tree recursive, because the calls form a tree. Examples: Fibonacci fib(n-1) + fib(n-2) and Tower of Hanoi (two calls for n-1 disks). Linear recursion (one call, like factorial) forms a chain instead.
Algorithm TOH(n, from, to, aux)
- If n = 1: move disk 1 from
fromtoto; return. - TOH(n-1, from, aux, to).
- Move disk n from
fromtoto. - TOH(n-1, aux, to, from).
#include <stdio.h>
/* move n disks from 'from' to 'to' using 'aux' */
void toh(int n, char from, char to, char aux) {
if (n == 1) { /* base case */
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
toh(n - 1, from, aux, to); /* step 1 */
printf("Move disk %d from %c to %c\n", n, from, to); /* step 2 */
toh(n - 1, aux, to, from); /* step 3 */
}
int main(void) {
toh(3, 'A', 'C', 'B');
return 0;
}
Recursion tree for 3 disks, call TOH(3, A, C, B)
TOH(3,A,C,B)
[4: disk 3 A->C]
/ \
TOH(2,A,B,C) TOH(2,B,C,A)
[2: disk 2 A->B] [6: disk 2 B->C]
/ \ / \
(1,A,C,B) (1,C,B,A) (1,B,A,C) (1,A,C,B)
[1: A->C] [3: C->B] [5: B->A] [7: A->C]
Moves are printed in in-order (left subtree, node, right subtree): 1 to 7.
Move sequence (verified by running the algorithm):
| Move | Disk | From | To | Pegs after the move (A / B / C) |
|---|---|---|---|---|
| 1 | 1 | A | C | 3,2 / - / 1 |
| 2 | 2 | A | B | 3 / 2 / 1 |
| 3 | 1 | C | B | 3 / 2,1 / - |
| 4 | 3 | A | C | - / 2,1 / 3 |
| 5 | 1 | B | A | 1 / 2 / 3 |
| 6 | 2 | B | C | 1 / - / 3,2 |
| 7 | 1 | A | C | - / - / 3,2,1 |
Calls = 2³ − 1 = 7, tree depth = 3, moves = 7.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- TOH algorithm and recursion tree · Data Structure and Algorithm, chapter 5 · asked 2×
- TOH for 3 disks and recursion principle · Data Structure and Algorithm, chapter 5
- TOH problem with solution for n disks · Data Structure and Algorithm, chapter 5 · asked 2×
- Recursion properties, Fibonacci, TOH algorithm · Data Structure and Algorithm, chapter 5
- Box trace and TOH recursion tree · Data Structure and Algorithm, chapter 5
- Recursion tree for Tower of Hanoi, 4 disks · Data Structure and Algorithm, chapter 5