Leaf-balanced binary tree 2026-10-24
A leaf-labelled binary tree is leaf-balanced when the leaf counts of the two subtrees at every internal node differ by at most one. Splitting a finite nonempty list into pieces of sizes and and applying the same construction recursively preserves the original leaf order and gives this balance condition. Both pieces are nonempty for and strictly shorter than the input; induction proves termination and balance. This leaf-count convention is different from demanding equal subtree heights.
Linear flattening of a binary tree 2026-10-24
For a leaf-labelled binary tree, define
go (One x) acc = x:acc and go (Two l r) acc = go l (go r acc), then apply go t []. The invariant in the title follows by structural induction and associativity of list concatenation. It proves preservation of leaf order. Each leaf supplies one output constructor and each internal node requires constant bookkeeping, giving linear time in the number of nodes. By contrast, flattening both subtrees and concatenating their results can copy prefixes of sizes on a left-branching tree, taking quadratic time. The accumulator is the already-known suffix in a difference list representation.For the paper's leaf-labelled binary tree, the combining operation receives the results of the two subtrees, and the other argument handles a leaf:
foldTree :: (a -> b) -> (b -> b -> b) -> Tree a -> b
foldTree f g (One x) = f x
foldTree f g (Two l r) = g (foldTree f g l) (foldTree f g r)Its constructor equation is
foldTree One Two = id. More generally, a function h satisfying h (One x) = f x and h (Two l r) = g (h l) (h r) equals foldTree f g on finite trees, by structural induction. This is the tree fold specialized to a datatype with labels only at leaves, rather than at internal nodes.