- Asked 2/14
- 2069 Poush · 3+5 marks
- 2070 Magh · 5 marks
TOH algorithm and recursion tree
Short answer
Algorithm TOH(n, from, to, aux): if n=1, move disk from to; else TOH(n-1, from, aux, to); move disk n; TOH(n-1, aux, to, from). For n=3, the recursion tree has root TOH(3,A,C,B) with left child TOH(2,A,B,C) and right child TOH(2,B,C,A); nodes at depth n-1 execute moves in in-order, producing 7 moves.
Write an algorithm for TOH problem. Hence find all solutions for three disks from your algorithm, showing recursion tree for the same.
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;
}
All solution steps for three disks (call TOH(3, A, C, B))
Output (verified by running the algorithm):
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
| 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 |
Recursion tree for 3 disks
Each node is a call TOH(n, from, to, aux). A move is performed at each node between its left and right subtree calls.
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.
The tree has 2³ − 1 = 7 nodes, so 7 moves are made. Number of calls for n disks = 2ⁿ − 1, and the depth of the tree is n.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Tree recursion and TOH with n disks · Data Structure and Algorithm, chapter 5
- Recursion properties, Fibonacci, TOH algorithm · Data Structure and Algorithm, chapter 5
- 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×
- 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