Chapter 12 · Simulation

Recursion Visualizer

← Chapter 12
    Call stack (top = running)
    Recursion tree runningon the stackbase casefrom memo

    Output

    Recursion Visualizer

    Purpose: see how a recursive method calls itself, how each call opens a separate frame on the call stack, how the recursion stops at the base case, and how the return values are carried up to the caller.

    How to use it

    1. Choose the method and the parameters. Step ▶ shows each call, the base case and each return separately; there are also Back, Play, Reset and a speed control (keyboard: → / ←).
    2. Top right is the call stack: a new frame is pushed on top, turns green with return and is popped in the next step. A suspended frame shows what it is waiting for (e.g. 4 * factorial(3) = ?).
    3. Below is the recursion tree: each node is a call; the return value is written under the node.
    4. In Fibonacci, turn on the Memoization box: computed values are written into the memoTable array, and when the same call comes again the subtree is not opened. The table on the left compares the call counts of the two versions.
    5. Try it yourself: predict the value at every (non-base) return, and in Hanoi the move that will be printed (e.g. A->C).

    Reminders

    • Every recursive method has two mandatory parts: the base case and the recursive case, which calls itself on a smaller problem.
    • Without memoization fib(n) computes the same subproblems over and over: the number of calls is 2·fib(n+1) − 1; in the memoized version it is 2n − 1.
    • In Hanoi, 2n − 1 moves are printed for n disks.

    Related slides: Chapter 12 · Recursion (recursive factorial, Towers of Hanoi, recursive power, the call stack, the Fibonacci problem, memoization).