← Tree Recursion · guided lesson

Tree Recursion

1 / 22 · story

the story

Tree recursion (solve the children, combine)

Every tool here exists because something was too slow or broke without it. Here is what.

1960 · John McCarthy

In his 1960 Lisp paper, McCarthy built all data from ordered pairs: an S-expression is a pair whose two parts are atoms or smaller S-expressions — a binary tree. He then defined functions on them recursively. His equal says two trees are equal if they are the same atom, or if their first halves are equal and their second halves are equal — the same check as LeetCode's Same Tree. His subst rebuilds a tree from its two rebuilt halves. Every "solve left, solve right, combine" function in this chapter has that shape.

the problem it solved

Computing anything about a nested structure — equality, size, a transformed copy — with a function as short as the structure's definition.

why it matters: without it

Every subtree question would be re-asked from scratch at each ancestor — O(n²) instead of O(n) on deep trees.

sources: McCarthy — Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I (CACM, 1960) ↗ · McCarthy (1960) — the section defining S-expressions, equal and subst ↗

also in this chapter: Pass information down (top-down parameters) · Return one thing, record another (global best) · Lowest common ancestor · Rebuilding a tree from traversals · Subtree ids (hash-consing): equal subtrees, equal numbers