Transcript
How big is this folder? It holds files, and other folders, which hold more files and more folders. You could write a long list of steps for every level. Or write one short rule that keeps using itself. Today: a function that calls itself. Recursion.
Here's the rule. The size of a folder is the size of its files, plus the size of each folder inside it. To use it on home, we need the size of photos. So we use the same rule on photos, and then on the folders inside photos. Each call hands the same question to a smaller folder, down and down, until a folder has no folders inside it. There, the answer is just its files. Then the answers travel back up. Each folder adds them together, until home has its total.
That bottom case, a folder with no folders inside, is called the base case. Every recursive function needs one. Without it, the function would call itself forever, like a folder that somehow holds itself.
How does the computer keep track of all these unfinished calls? With the stack from the last episode. Each call is pushed onto the call stack, holding its own folder and its own running total. When a call finishes, it pops off, and the one below picks up where it left off. If the calls go too deep, the stack runs out of room. That's the famous error: stack overflow.
Anything written with recursion can also be written with a loop, and a stack that you manage yourself. Pick whichever is clearer. For trees and anything nested, recursion usually wins.
Recursion: solve one small piece, and trust the same rule to handle the rest. Next time, the same idea finds anything in a sorted list in about twenty steps. Binary search. See you there.
Next episode: binary search, finding anything in a sorted list in about twenty steps.