Recursion

A folder can contain files and other folders. To calculate its total size, we need to calculate the size of each folder inside it, which may contain more folders of its own.

Recursion occurs when a function calls itself. In algorithms, we use this idea to solve a problem by breaking it into smaller instances of the same problem. A recursive solution needs a base case that stops the calls and a rule for obtaining the answer from smaller instances.

A simple recursive function

Factorial

Before working with nested folders, consider a simpler problem: calculating the factorial of a non-negative integer. The factorial is n!=1\cdot2\cdot\ldots\cdot n, and 0!=1.

To calculate , we can first calculate and multiply the result by 4. The same rule applies to , and . Eventually, we reach , whose value is already known.

Since n!=n\cdot(n-1)! for n>0, the function fact(n) calls fact(n - 1) and multiplies the returned value by n. This gives us three parts of a recursive solution:

  1. A base case, n == 0, which returns 1 without another call.

  2. A recursive call, fact(n - 1), that solves a smaller problem.

  3. Combining the result with n to obtain the current answer.

Every recursive branch must make progress toward a base case. Here n decreases by 1 until it reaches 0. Without a reachable base case, calls can keep accumulating until the program runs out of stack memory.

The program reads an integer (0\le n\le20) and prints its factorial:

#include <iostream>
using namespace std;

long long fact(int n) {
    if (n == 0) return 1;         // base case
    long long rest = fact(n - 1); // smaller problem
    return n * rest;              // combine, return
}

int main() {
    int n;
    cin >> n;
    cout << fact(n) << '\n';
}

For n = 4, the calls proceed from fact(4) down to fact(0). The base case returns 1. Then fact(1) returns 1\cdot1=1, fact(2) returns 2\cdot1=2, fact(3) returns 3\cdot2=6, and finally fact(4) returns 4\cdot6=24.

The call stack of fact(4) while fact(0) runs: five calls in a row from n = 4 on the left to n = 0 on the right, with arrows for the calls going right, and under each call its return value: 24, 6, 2, 1, 1.

Fig. 1. The calls go to the right. The answers, under the calls, come back to the left: 1, 1, 2, 6, 24.

The call stack

Each invocation of a function has its own local variables and by-value parameters. When it makes another call, execution of the outer call pauses. After the inner call returns, the outer call continues from where it stopped. For example, when fact(3) receives 2 from fact(2), its own n is still 3, so it returns 6.

The active calls form the call stack. A new call is placed on top of the stack. When it returns, it is removed, and the previous call resumes. This is the last-in, first-out principle of a stack.

Recursive and iterative solutions

Recursion does not automatically make a solution faster. Factorial can also be calculated using a simple loop.

Recursion with multiple calls

Return to the folder problem from the introduction. Consider folder /a, which contains files and the folders /a/b and /a/c. Its total size equals the size of its own files plus the total sizes of both subfolders.

The function size(folder) starts with the size of the folder's own files and recursively adds the size of each child folder. We can describe the algorithm without yet deciding how to represent folders in a program:

size(folder):
    total = size of its own files
    for each child folder:
        total += size(child)
    return total

A folder with no child folders is a base case: the loop makes no recursive calls and the function returns the size of its own files. A base case does not have to be a separate if statement.

Fig. 2 runs size("/a") on a small folder tree. Under the tree, the calls that have started and not finished yet form a row, the newest on the right.

The calls of size of /a on the folder tree, with the call stack under it, step 1.

Each folder shows the size of its own files. No call has started yet.

1/13

Fig. 2. The calls of size("/a"). A number beside a folder is its total so far; green means the folder is finished. The blue folder is the call that runs, the red lines lead to it from the calls that wait, and the boxes under the tree are the call stack.

The calls for /a/b/d and /a/b/e return 5 and 4, so /a/b returns 3+5+4=12. The call for /a/c returns 1+6=7. Finally, /a combines these results with its own files: 2+12+7=21 MB. Each paused call keeps its own running total and resumes after its child returns.

Implementation

The program reads folders (1\le n\le1000), numbered from 1 to . Folder 1 is the main folder. Every other folder is directly inside exactly one parent folder, and all folders are contained within folder 1, directly or through other folders. For each folder i, the input contains the size of its own files (an integer from 0 to 10^9) and its parent p (0 for the main folder).

Store the list of folders directly inside each folder in a vector. Reading that folder i is inside folder p adds i to children[p]. The folders in Fig. 2 are numbered as follows:

Folder

Path

Parent

Children

1

/a

0

2, 3

2

/a/b

1

4, 5

3

/a/c

1

6

4

/a/b/d

2

None

5

/a/b/e

2

None

6

/a/c/f

3

None

Input:

6
2 0
3 1
1 1
5 2
4 2
6 3

Output:

21 12 7 5 4 6
#include <iostream>
#include <vector>
using namespace std;

vector<long long> own, total;
vector<vector<int>> children;

long long size(int v) {
    long long t = own[v];
    for (int c : children[v]) {   // base case: a folder with nothing inside skips the loop
        t += size(c);             // smaller problem, combine
    }
    total[v] = t;
    return t;                     // return
}

int main() {
    int n;
    cin >> n;
    own.resize(n + 1);
    total.resize(n + 1);
    children.resize(n + 1);
    for (int i = 1; i <= n; i++) {
        int p;
        cin >> own[i] >> p;
        if (p != 0) children[p].push_back(i);
    }
    size(1);
    for (int i = 1; i <= n; i++) cout << total[i] << ' ';
    cout << '\n';
}

The function size(v) accumulates the sizes of all child folders, stores the result in total[v] and returns it to its caller. The running total t is local to each invocation: a child call has its own t and cannot overwrite the parent's running total. Each folder is processed once and each parent-child connection is examined once, so the traversal takes time. The input representation and stored answers use memory; the additional call-stack memory depends on how deeply the folders are nested.

Team sizes

The same shape counts people in a company. Person 1 is the boss. People 2, 3 and 4 report to person 1, people 5 and 6 report to person 2, and person 7 reports to person 4. A person's team is that person plus the teams of everyone who reports to them.

A reporting tree drawn downwards: persons 2, 3 and 4 report to person 1, persons 5 and 6 report to person 2, and person 7 reports to person 4. Persons 3, 5, 6 and 7, with nobody reporting to them, have team size 1 beside them; persons 1, 2 and 4 have a question mark.

Fig. 3. A person with nobody reporting to them has a team of 1. The other teams are for you to fill in.

The function starts like size, with the person themself counted as 1.

int team(int v) {
    int t = 1;  // the person v
    for (int c : reports[v]) {
        // combine: your line here
    }
    return t;
}

Recursion depth and running time

The total number of calls and the maximum number of simultaneous calls are different quantities. The latter is called the maximum recursion depth. We count the initial call as part of the depth.

Consider two arrangements of seven folders. In the first, the main folder contains two folders, and each of those contains two more folders. In the second, the seven folders form a single chain of nested folders. Both arrangements require seven calls, but their maximum depths are 3 and 7, respectively.

Factorial makes n+1 calls and has depth n+1. The folder traversal makes calls, but its maximum depth is , the number of folders on the longest path from the main folder to an innermost folder. Its running time is , while the call stack uses memory because each call requires constant additional space. Running time depends on all the work performed, not just the deepest chain of calls.

Repeated recursive calls

In the folder problem, every folder is visited once. However, multiple recursive calls do not always solve different subproblems. Sometimes the same result is calculated again and again.

Consider calculating the -th Fibonacci number. The sequence is defined by F_0=0, F_1=1 and F_n=F_{n-1}+F_{n-2} for n\ge2. This definition translates directly into a recursive function. For example, we can evaluate it for small inputs such as 0\le n\le20:

long long fib(int n) {
    if (n < 2) return n;                // base case
    return fib(n - 1) + fib(n - 2);     // smaller problem, combine, return
}

The naive Fibonacci function recomputes the same smaller values many times. For example, fib(5) makes 15 calls, but only five can be active at once. Each call creates at most two new calls, and the maximum depth is for n\ge1. Across all depths there can be at most 1+2+4+\dots+2^{n-1}=2^n-1 calls. Since each call does constant work apart from its recursive calls, the running time is bounded by O(2^n). The actual running time grows exponentially, while call-stack memory is only .

Similar techniques

Merge sort and Quicksort use recursion to sort smaller parts of an array and obtain a sorted result.

Depth-first search often uses recursion to explore the structure of a tree or graph.

Backtracking uses recursion to explore possible choices, undoing a choice when returning from its recursive call.

Dynamic programming avoids repeated work when the same smaller problems occur many times.

Practice

Was this page helpful?