Lessons · #5 of 11

Binary Trees

One node, two children — every recursive data structure

Binary tree · traversal orders

pick a traversal → · preorder / inorder / postorder / level
init

Try it: Insert a few values. Then try each traversal — preorder, inorder, postorder, level — and watch the visit order light up under the tree.

Why it matters

Trees are the natural structure for hierarchical data: file systems, HTML documents, organization charts, decision trees. Binary trees are the foundation for BSTs, heaps, and expression parsing.

The idea

Imagine a family tree, but each person has at most two children (left and right). Start from a single root ancestor.

That's a binary tree. Each node has at most two children.

Trees unlock new ways to organize data:

Traversals visit nodes in different orders:

Key takeaways

Going deeper

A complete binary tree fills each level before starting the next (except possibly the last level). A full binary tree has every node with 0 or 2 children. A perfect binary tree is both complete and full. These distinctions matter for heap implementations (which require complete) and tree balancing.

The "max nodes at level k = 2ᵏ" formula falls out by induction: level 0 has one node (the root); each level has at most twice the previous. Summing the geometric series from level 0 to height h yields 2^(h+1) − 1 nodes max. Inverting: a balanced tree of n nodes has height ⌊log₂ n⌋.

In the wild

Math details

Tree properties
max nodes at level k 2ᵏ
max nodes in tree, height h 2ʰ⁺¹ − 1
min height, n nodes ⌊log₂ n⌋
max height (degenerate) n − 1
Traversal time
O(n) — every node visited exactly once
Space
recursive traversal O(h) on the call stack
iterative (BFS) O(w) where w is the widest level

Implementation

Binary Tree Node

struct TreeNode<T> {
    data: T,
    left: Option<Box<TreeNode<T>>>,
    right: Option<Box<TreeNode<T>>>,
}

// In-order traversal (recursive)
fn inorder(node: Option<&Box<TreeNode<T>>>) {
    if let Some(n) = node {
        inorder(n.left.as_ref());
        process(n.data);
        inorder(n.right.as_ref());
    }
}

Traversal Orders

Practice

Three problems, each teaching a different recursion shape:

Browse all practice problems