Recursion Apan Qasem Texas State University Spring 2011
When to use Recursion? Some problems naturally fall in this category Something defined in terms of itself Self-referential Recurrence relations or equations Snowflake
When to use Recursion? Recursive data structures Trees Lists LISP and Scheme based on recursive lists
Why use recursion? Recursion for profit Sometimes can get a faster a solution Recursion for readability “elegant” solutions smaller code size
The Fibonacci Sequence Classic example of natural recursion To find n th Fibonacci need to know the previous two Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2) Self-reference
Recursion Mechanics Base case Trivial (no computation) Can be one or more Non-recursive way of getting out function Recursive case Decompose problem as a smaller version of itself Result in eventually reaching the base case Somehow be useful to solving the original problem
Recursive Case Examples Parameter specifies smaller problem recurse(n - 1); recurse(ptr->Next); Call may involve computation Often value “returned” to caller return n * factorial(n – 1) May have multiple calls walk(node->leftChild); walk(node->rightChild);
Base Case Examples Exact condition if (n == 0) return 1; Range if (n < 2) return 1; if (n > 0) return 1; Other if (ptr == NULL) return;
Towers of Hanoi Move all rings from peg A to peg C Only one disc may be moved at a time. A disc can be placed either on empty peg or on top of a larger disc