1 of 4

Your RightSignal

Algorithms · 1 of 131 / 3

Recursion

The concept

How your computer works out the size of a folder full of folders

Recursion means solving a problem by solving a smaller copy of the same problem, then using that answer. A recursive function is one that calls itself on the smaller copy.

Take a folder Photos with two files, 3 MB and 1 MB, and a subfolder Trip holding a 5 MB file. Its size is its own files plus each subfolder's size. Measuring Trip is the same job on a smaller folder, so the function calls itself.

Every recursion needs two parts. The base case is small enough to answer directly, like a folder with no subfolders. The recursive case splits the job into smaller copies: add up my files, then ask each subfolder.

What it’s forDefines a folder's total size in terms of the sizes of its smaller subfolders.

size(F) = Σ file sizes in F + Σ size(S) for each subfolder S

F
the folder being measured, e.g. Photos
S
each subfolder directly inside F, e.g. Trip
size(S)
the same function called on a smaller folder, the recursive step
Σ
add up all of them; with no subfolders this part is 0, the base case

What it givesThe total bytes in a folder and everything nested inside it, however deep.

  1. size(Trip) = 5 + 0 = 5 MB (no subfolders: base case)
  2. size(Photos) = (3 + 1) + size(Trip)
  3. = 4 + 5 = 9 MB