Skip to main content

TOH for 3 disks and recursion principle

Short answer

For three disks, TOH(3,A,C,B) produces moves A->C, A->B, C->B, A->C, B->A, B->C, A->C, with calls=7=2^3-1. The recursion tree has root TOH(3,A,C,B) with two TOH(2) subtrees, and in-order traversal prints the moves. Basic recursion principle: solve a smaller instance plus a base case, e.g. fact(n)=n*fact(n-1) with fact(0)=1.

Explain a Tower of Hanoi for 3 disks and also generate recursion tree. Explain the basic principle of recursion with example.

Tower of Hanoi for 3 disks

Pegs A (source), B (auxiliary), C (destination). Three disks, 1 (smallest) to 3 (largest), are on A. Rules: move one disk at a time, take only the top disk, never place a larger disk on a smaller one. Solution = TOH(3, A, C, B), where TOH(n, from, to, aux) does: TOH(n-1, from, aux, to); move disk n from→to; TOH(n-1, aux, to, from).

MoveDiskFromToPegs after the move (A / B / C)
11AC3,2 / - / 1
22AB3 / 2 / 1
31CB3 / 2,1 / -
43AC- / 2,1 / 3
51BA1 / 2 / 3
62BC1 / - / 3,2
71AC- / - / 3,2,1

Recursion tree

                    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.

Calls = 7, moves = 7 = 2³ − 1.

Basic principle of recursion

A problem is solved by expressing it in terms of a smaller instance of the same problem, plus a base case that is solved directly. Every recursive call must move closer to the base case, otherwise it never stops.

Example: factorial

  • Base case: fact(0) = 1
  • Recursive case: fact(n) = n × fact(n-1)
int fact(int n) { return (n == 0) ? 1 : n * fact(n - 1); }

fact(3) = 3 × fact(2) = 3 × 2 × fact(1) = 3 × 2 × 1 × fact(0) = 6. The calls are stored on the stack and are resolved in reverse order when the base case returns.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 5 questions →