Data Structures and Algorithms
Recursion
What recursion means
Recursion is a problem-solving technique in which a function calls itself to solve smaller instances of the same problem. The repeated calls continue until they reach a condition that tells them to stop.
A recursive function has a general structure:
Check whether the problem has reached a stopping point.
If it has, return without making another recursive call.
Otherwise, perform some work and call the function again on a smaller or simpler input.
A function that calls itself but never reaches a stopping condition keeps creating calls until the program runs out of stack space. This is commonly reported as a stack overflow.
The three essential parts of a recursive function
1. Base case
The base case is the stopping condition. It handles an input small or simple enough to solve directly and prevents recursion from continuing indefinitely.
For example, when printing a requested number of messages, a count of zero means there is nothing left to print:
If n≤0, return.
A base case should match the problem’s valid stopping point. It is also useful to consider boundary or invalid inputs so that they do not cause unnecessary recursive calls.
2. Work, or business logic
The work is the operation the function performs for the current call. It may print a value, calculate something, or process a node in a data structure.
3. Recursive call with progress
The function calls itself on a smaller or simpler version of the problem. The input must make progress toward the base case; otherwise, the recursion may never stop.
For example, if the function has already printed once, it can reduce the remaining count from n to n−1 before the next call.
A reliable starting point when designing recursion is to identify the base case first, then determine what work each call performs and how the next call moves closer to the base case.
Example: Print a message a specified number of times
Suppose a function must print a message n times. Its logic is:
If n≤0, stop.
Print the message.
Call the function with n−1.
For an initial call with n=3, the calls process counts 3, 2, 1, and finally 0. The call with count 0 reaches the base case and does not print.
The input shrinks by one each time, so the base case is eventually reached.
Recursion and iteration
A loop and a recursive function can both repeat work. A loop repeats a block of instructions directly; recursion repeats work by creating a sequence of function calls.
For example, printing all the elements of an array can be done either by advancing a loop index or by calling a function with the next index. The two approaches may produce the same output, but their structure and resource use differ.
Recursion is not automatically faster or more memory-efficient than iteration. It can make a solution clearer when a problem has a naturally recursive structure, but each recursive call uses space on the call stack. An iterative solution may use less memory when it can replace those calls with a loop.
The choice depends on the problem:
Recursion can express repeated or branching structures naturally.
Iteration can be preferable when stack usage is a concern or the recursive formulation is less clear.
The time complexity depends on the algorithm, not simply on whether it is written recursively or iteratively.
Recursive traversal of an array
An array can be processed recursively by passing both the array and the current index.
For an array with length L, the index begins at 0‘.Eachcallprocessesthecurrentelementandadvancestheindex.ThebasecaseisreachedoncetheindexisatleastL$.
Print elements in their original order
The steps are:
If the current index i satisfies i≥L, return.
Process or print the element at index i.
Recursively process the array starting at index i+1.
For the array [1,2,3], the function prints 1, then 2, then 3.
The work occurs before the recursive call, so each element is printed as the function moves forward through the array.
Print elements in reverse order
The same traversal can produce the reverse output by changing the position of the work:
If i≥L, return.
Recursively process the array starting at index i+1.
Print the element at index i.
For [1,2,3], the calls first advance to the end of the array. As they return, they print 3, then 2, then 1.
The base case and input progression remain the same; only the position of the printing operation changes.
The call-and-return process
Recursion has two phases:
Descent: Calls are made until one reaches the base case.
Unwinding: Once the base case returns, earlier calls resume and finish any work that follows their recursive call.
This explains why placing work before or after a recursive call changes the order of results:
Work before the recursive call happens during descent.
Work after the recursive call happens during unwinding.
A recursive call does not erase the earlier calls. Each call remains suspended with its own parameters and execution position until the deeper call returns.
For array printing in reverse, the calls move from index 0 toward index L. Once the call at index L returns, the call at index L−1 resumes and prints its element. The remaining calls then resume in turn.
How the call stack supports recursion
When a function is called, the runtime keeps information about that call, including its parameters and where execution should continue after the function returns. This information is stored in the call stack.
The stack follows a last-in, first-out order:
The most recently added call is the first one to return.
Earlier calls remain waiting beneath it.
For recursive array printing in reverse order, each call stores its current index. When the base case is reached, calls return in the opposite order from which they were made. That return order produces the reverse output.
The call stack is the mechanism that lets a recursive function pause, call itself again, and later resume where it left off.
If recursion continues without reaching a base case, calls keep accumulating on the stack. Eventually, the available stack space may be exhausted.
Example: Preorder traversal of a tree
A tree is a structure in which nodes may have child nodes. Recursive traversal suits trees because the same processing pattern can be applied to a node and then to its subtrees.
A preorder traversal follows this order:
If the current node is
null, return.Visit or process the current node.
Traverse the left child.
Traverse the right child.
The base case is a null node. The recursive calls apply the same procedure to the left and right subtrees.
This approach expresses the structure of a tree directly. An iterative traversal is also possible, but it typically requires explicitly managing traversal state, such as with a stack.
Where recursion is useful
Recursion is a foundational technique that appears in many data-structure and algorithm problems, including:
Sorting: Merge sort and quicksort use recursive subproblems.
Linked lists: Some operations, including reversal, can be expressed recursively.
Trees and graphs: Recursive traversal follows connected or nested structures.
Dynamic programming: Many dynamic-programming solutions begin with a recursive description of a problem, even if they are later optimized.
The key advantage is often clarity: when a problem consists of smaller instances of the same problem, recursion can make that relationship explicit.
The Tower of Hanoi as a recursive challenge
The Tower of Hanoi is a classic example of a problem suited to recursive reasoning. It has three towers and n disks of different sizes. The disks begin stacked on one tower, ordered with the largest at the bottom and the smallest at the top.
The task is to move all disks to another tower, using the third tower as an auxiliary location, while following two rules:
Only one disk may be moved at a time.
A larger disk may never be placed on top of a smaller disk.
The problem illustrates why recursion is useful for tasks involving repeated, structured steps. A recursive solution breaks the overall goal into smaller versions of the same task. The specific move sequence and move count require further analysis.
Key points to remember
Recursion solves a problem through calls to the same function on smaller or simpler inputs.
Every recursive function needs a base case that stops further calls.
Each recursive call must make progress toward that base case.
The call stack stores active calls until deeper calls return.
Work before a recursive call occurs during descent; work after it occurs during unwinding.
Recursion can express problems involving repeated or branching structures clearly, but it uses stack space and is not inherently more efficient than iteration.

Ask anything
We've read this whole study set, so questions about it get the best answers.