Skip to main content

Recursion properties, Fibonacci, TOH algorithm

Short answer

Properties: self-call, base case, smaller subproblem, stack frames, results combined while returning. Recursive Fibonacci is not preferred because it repeats subproblems: fib(30) makes 2,692,537 calls, O(2^n) time and O(n) stack. TOH for three disks: A->C, A->B, C->B, A->C, B->A, B->C, A->C, total 7 moves.

State properties of recursion. Why is the recursive method for Fibonacci sequence not preferred? Write an algorithm for TOH problem and use it to find the solution for three disks.

Properties of recursion

  1. A recursive function calls itself, directly or indirectly.
  2. It has a base case (stopping condition) whose answer is known without further calls.
  3. Each recursive call works on a smaller or simpler version of the problem and moves toward the base case.
  4. Every call has its own parameters, local variables and return address, stored on the stack.
  5. The result is built while returning (unwinding) from the calls.
  6. Without a reachable base case the recursion is infinite and ends in stack overflow.

Why recursive Fibonacci is not preferred

fib(n) = fib(n-1) + fib(n-2), fib(0) = 0, fib(1) = 1. The same sub-problems are solved again and again: in fib(5), fib(3) is computed twice and fib(2) three times. The number of calls grows exponentially (fib(5): 15 calls, fib(30): 2,692,537 calls, counted by program), time is O(2ⁿ), and stack depth is n. An iterative loop gives the answer in n steps with constant memory.

TOH algorithm

TOH(n, from, to, aux):

  1. If n = 1, move disk 1 from from to to and return.
  2. TOH(n-1, from, aux, to).
  3. Move disk n from from to to.
  4. TOH(n-1, aux, to, from).

Solution for 3 disks: TOH(3, A, C, B)

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

Total 2³ − 1 = 7 moves.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 5 questions →