Recursion
A function that calls itself is recursive. It sounds circular, but it's the most natural way to handle anything built from smaller copies of itself: a folder full of folders, a team made of smaller teams, a puzzle that splits into smaller puzzles.
Two parts
Every recursive function has:
- a base case, small enough to answer directly, without calling itself;
- a recursive case, which answers by calling itself on something smaller and combining the results.
// size of a folder: its own files plus every folder inside it
func folderSize(f Folder) int {
total := f.Files // when there are no subfolders, this is the answer
for _, sub := range f.Subfolders {
total += folderSize(sub)
}
return total
}
Here the base case hides in the loop: a folder without subfolders doesn't loop at all and returns its own files. Each call works on a smaller part of the tree, so the calls always reach the bottom.
Trust the smaller call
The trick to writing recursion is not to trace every call in your head. Assume the call on the smaller part already returns the right answer, and ask only: how do I build my answer from those? "My team is me plus my reports' teams." "My depth is one more than my deepest report's."
Searching with recursion
Recursion can also look for something and report the way to it. Return a result that says "not found" (such as nil), and when a smaller call does find it, add the current step in front:
if rest := chain(reports, r, name); rest != nil {
return append([]string{top}, rest...)
}
Each call that waits keeps a little memory until it returns. Trees in puzzles are usually shallow enough; for a long chain, such as a path through a large grid, a loop with a stack (the previous chapter) is safer.
Task
This lesson's input is an organisation chart: each line is a manager, a colon, and the people who report to them. The first line names the head of the organisation. reports maps a name to their direct reports; someone with no line has no reports.
- Complete
teamSize(reports, name) int:nameplus everyone below them, at any level. - Complete
depth(reports, name) int: how many levels the team has. Someone with no reports has a depth of1. - Complete
chain(reports, top, name) []string: the people fromtopdown toname, both included, ornilwhennameis not intop's team.