Recursion and trees

Day 3

Rust for bioinformaticians

What this lecture is

Recursive data and recursive code. We’ll use a phylogenetic tree as the example throughout — first the data type, then the functions that walk it.

  • A tree is a type that contains itself: a node holds its children, which are nodes
  • Rust needs one extra ingredient — a small trick to give the compiler a fixed size — to make that type compile
  • Once we have the type, the functions almost write themselves

A real lineage tree — great apes

Before any code, here is the kind of object we are going to model — a real, small phylogeny:

A rooted phylogenetic tree drawn left-to-right. Root at left. Two branches leave the root: one descends to a Human-Chimp ancestor at 6 MYA, which splits to Human and Chimp tips at the present; the other branch is 9 MYA long and ends at the Gorilla tip. Branch lengths labelled in millions of years; a time axis at the bottom shows 9 MYA, 6 MYA, 3 MYA, today. A Newick string `((Human:6, Chimp:6):3, Gorilla:9);` shown in a callout.

A great-apes phylogeny: Human and Chimpanzee share an ancestor ~6 million years ago; Gorilla joins higher up at ~9 MYA. Branch lengths are proportional to time.

The shape is what we want to capture in Rust: two tips share a recent common ancestor; a third tip joins higher up. Throughout the lecture we’ll use the same shape with abstract names (A, B, C) so the code stays compact — but the structure is the same as Human / Chimp / Gorilla above.

Phylogenetic trees — what we want to model

A phylogeny (a branching diagram of evolutionary relationships) is built from internal nodes (inferred common ancestors) and tips / leaves (present-day samples).

At each node we record a name (at tips) and a branch length — the evolutionary distance to the parent.

A small 3-tip tree shown three ways: a graphical tree, the Newick string ((A:0.1,B:0.2):0.3,C:0.5);, and the equivalent Rust Node::Internal { ... } literal.

Same tree as a picture, a Newick string, and a Rust enum literal.

Why this won’t compile yet

// This does NOT compile:
enum Node {
    Internal { left: Node, right: Node },
    Leaf,
}
// error[E0072]: recursive type `Node` has infinite size

size(Node) = 1 + 2 × size(Node) — no fixed answer.

The 1 is the variant tag; the 2 × size(Node) is two child Nodes inlined into the parent — that’s the part with no finite answer.

The fix: store a pointer to each child instead of the child itself.

Box<T> — indirection makes it work

  • Box<T> = a small handle (8 bytes) that points to a value stored elsewhere in memory (“the heap” [the region the program allocates from at runtime when sizes aren’t known up front]).
  • The parent’s size is now fixed; the child lives somewhere else.
Two-panel diagram. Left panel headed enum Node { Internal { left: Node, right: Node }, Leaf } in red with subtitle compile error: recursive type has infinite size shows six nested Node boxes Russian-doll-style, the innermost containing ellipses and ...forever, with the footer size(Node) = 1 + 2 × size(Node), no fixed answer — compiler rejects. Right panel headed enum Node { Internal { left: Box<Node>, right: Box<Node> }, Leaf } in green with subtitle Box<T> is a heap pointer — always 8 bytes shows a blue Stack region containing a Node::Internal with two pointer cells left: and right:, labelled 2 × 8 byte pointers; on the right an orange Heap region holds two child Node::Leaf boxes labelled fixed size, with blue arrows from the pointer cells to the child boxes. Footer: size(Node) = tag + 2 × 8 (fixed); children live on the heap, the parent is a small record on the stack.

Box turns infinite recursion into a fixed-size pointer.

A phylogenetic tree as a recursive enum

enum Node {
    Leaf     { name: String,        branch_length: f64 },
    Internal { branch_length: f64,  children: Vec<Node> },
}

A leaf is a tip species; an internal node groups child sub-trees. Vec<Node> provides the indirection (heap-allocated children) and the variable arity (two children or twenty — same type).

Building a tree by hand

The cleanest way to test a tree function: hard-code a small tree in main and call your function on it.

fn main() {
    // The tree ((A:0.1, B:0.2):0.3, C:0.5);
    let tree = Node::Internal {
        branch_length: 0.0,
        children: vec![
            Node::Internal {
                branch_length: 0.3,
                children: vec![
                    Node::Leaf { name: "A".to_string(), branch_length: 0.1 },
                    Node::Leaf { name: "B".to_string(), branch_length: 0.2 },
                ],
            },
            Node::Leaf { name: "C".to_string(), branch_length: 0.5 },
        ],
    };

    println!("{} tips", count_tips(&tree));
}

The repetition is on purpose: when you can read the structure of the literal, you can read any recursive enum.

A two-tip warm-up — the simplest tree

Before counting tips of the 3-tip tree, here’s the absolute minimum:

let tiny = Node::Internal {
    branch_length: 0.0,
    children: vec![
        Node::Leaf { name: "A".to_string(), branch_length: 0.5 },
        Node::Leaf { name: "B".to_string(), branch_length: 0.7 },
    ],
};

Two leaves under one ancestor. If count_tips(&tiny) returns 2, your function works on the base cases (leaves) and on a one-deep recursive case. The 3-tip tree on the next slide adds a second level.

Recursive functions — match the type

To count the tips of a tree:

if the tree is a Leaf, the answer is 1. If Internal, the answer is the sum of the tip counts of each child.

The explicit shape — an accumulator and a loop:

fn count_tips(node: &Node) -> usize {
    match node {
        Node::Leaf { .. } => 1,
        Node::Internal { children, .. } => {
            let mut total = 0;
            for child in children {
                total += count_tips(child);
            }
            total
        }
    }
}

The idiomatic Rust version

The idiomatic Rust version collapses the loop into an iterator chain:

fn count_tips(node: &Node) -> usize {
    match node {
        Node::Leaf { .. } => 1,
        Node::Internal { children, .. } =>
            children.iter().map(count_tips).sum(),
    }
}

Same code, same speed — the second is what you’ll see in Rust idiom.

Counting tips — step by step

Count accumulates bottom-up — leaves return 1, each internal node sums its children.

The example tree shown with no annotations.

Step 1: the example tree with no annotations.

The same tree with each leaf labelled with the return value 1.

Step 2: each leaf returns 1.

Internal node now labelled with 2.

Step 3: internal node (A,B) sums its children — 1 + 1 = 2.

Root labelled 3 — final answer.

Step 4: root sums its children — 2 + 1 = 3.

Another walk: deepest leaf

The depth of a tree is the longest path from the root to any leaf. A leaf is at depth 0. An internal node is at depth 1 + the max depth among its children.

fn max_depth(node: &Node) -> usize {
    match node {
        Node::Leaf { .. } => 0,
        Node::Internal { children, .. } =>
            1 + children.iter().map(max_depth).max().unwrap_or(0),
    }
}

Same shape as count_tips: one arm per variant, recursive call per child, combine with an iterator method.

About the unwrap_or(0): .max() on an empty list returns None (no answer); unwrap_or(0) says “treat that as 0”. An internal node with no children is biologically odd but allowed by the type — this keeps the function total.

Max depth — step by step

Same bottom-up flow as tip-counting, but the combiner is max over branch-lengths instead of sum.

The example tree with no depth annotations.

Step 1: the tree without depth annotations.

Each leaf labelled with its branch length.

Step 2: each leaf returns its own branch length (0.1, 0.2, 0.5).

Internal node labelled 0.5.

Step 3: internal (A,B) returns 0.3 + max(0.1, 0.2) = 0.5.

Root labelled 0.5 — final answer.

Step 4: root returns 0.0 + max(0.5, 0.5) = 0.5. Final depth = 0.5.

Collecting all tip names

Same recursion shape, different return type — instead of a number, a list of strings:

fn collect_tip_names(node: &Node) -> Vec<String> {
    match node {
        Node::Leaf { name, .. } => vec![name.clone()],
        Node::Internal { children, .. } => {
            children.iter()
                .flat_map(|child| collect_tip_names(child))
                .collect()
        }
    }
}

For ((A:0.1, B:0.2):0.3, C:0.5); this returns ["A", "B", "C"].

flat_map (a built-in iterator method that maps and flattens in one step) collects each child’s Vec of names and chains them together — the recursive pattern is identical to count_tips, but the return type changed.

More walks of the same shape

Once you have the recursion pattern, biology walks pour out:

Function Returns Combine
total_branch_length(node) f64 sum of own + all children’s
count_internal_nodes(node) usize 1 + sum of children’s (Leaf returns 0)
find_tip(node, name) Option<...> first matching leaf, else recurse
tips_at_depth(node, d) Vec<String> tips whose root-distance equals d
prune_by_name(node, names) Option<Node> drop subtrees whose only tips are in names

All the same shape: match Leaf vs Internal, base case + recursive case, combine the children’s answers. The combinator changes (+, max, concat, first match, etc.) but the skeleton is identical.

Recursion has a depth cost

Every recursive call pushes a stack frame onto the call stack.

max_depth(root)
  max_depth(child_1)
    max_depth(grandchild_1a)
      max_depth(great_grandchild_1a_i)   ← deeper = more frames
        ...

The stack has a fixed size (a few megabytes by default). Very deep recursion can run out of room — a stack overflow.

When recursion is safe

When recursion depth matters:

  • Phylogenies: a few hundred internal nodes at most — well within the budget. Recursion is fine.
  • Long sequences: a million bases would mean a million frames — would crash. Use an explicit loop or an iterative work-list instead.

Rust does not guarantee tail-call optimisation; some other languages do, but you can’t rely on it here.

To the next lecture

Next lecture: when recursion isn’t enough — dynamic programming, with sequence alignment as the example.