F4.02 · part 1 of 3
Binary trees & recursive shape
A binary tree is defined by recursion: a node is {value, left, right},
and a subtree is either another node or nil. Every function over a tree follows that
definition — handle nil as the base case, and handle a node by combining the
results from its two subtrees. Size, height, and sum are the same recursion with a different combine step.
Because the data branches, the recursion branches too: two recursive calls per node instead of the one a list needed. Select a function to see its clauses and result over the seven-node tree.
Functions that fold a tree
Each function has a clause for nil and a clause for a node. The node clause makes
two recursive calls — one per subtree — and combines them. Select one and read its clauses and
result.
The function · select one
clause: size({v, l, r}) = 1 + size(l) + size(r)
result: 7 · base: size(nil) = 0
There are always exactly two clauses to get right: what an empty tree is worth, and how to fold a node from its two subtrees. Miss neither and the function is total — the recursion cannot run off the end.
References
Primary sources for this lesson, and where it connects in the course.
Sources
- Tree traversal — Wikipedia — depth-first and breadth-first orders.
- Okasaki, C. (1996). Purely Functional Data Structures. — trees, functionally.