Binary Trees
Picture a family tree — but a very strict one. Every person can have at most two children: a left child and a right child. That's a binary tree.
The person at the very top is called the root. People at the bottom with no children are called leaves. Everyone in between is an internal node.
Key vocabulary
- Root — the top node, the starting point
- Parent — a node that has children below it
- Child — a node directly below a parent
- Leaf — a node with no children
- Height — the number of edges on the longest path from root to a leaf
- Depth — how far a node is from the root
Why binary trees matter
Binary trees are everywhere in computer science. File explorers, compilers, databases — all use tree structures. The binary constraint (at most 2 children) makes them especially efficient to reason about and implement.
← → arrow keys to step · click elements to interact
Tree Traversals
Four ways to visit every node
"Traversal" means visiting every node exactly once. The order you visit them depends on which traversal you use. Think of it like reading a book — do you read the chapter title first, or the content?
Pre-order: Root → Left → Right
Visit the root before its subtrees. Like reading a book's table of contents before the chapters. Used to copy a tree or serialize its structure.
In-order: Left → Root → Right
Visit the left subtree, then the root, then the right subtree. For a Binary Search Tree, in-order traversal gives you all values in sorted ascending order — a very handy property.
Post-order: Left → Right → Root
Visit children before the parent. Useful when you need to process or delete children before their parent — like calculating folder sizes (you need sub-folder sizes before the folder total).
Level-order: BFS row by row
Visit nodes level by level, left to right — like reading a paragraph normally. Uses a queue rather than recursion. Great for finding the shortest path or printing a tree visually.
Complexity
Full vs. Complete vs. Perfect
These are special shapes that binary trees can have:
- Full binary tree — every node has either 0 or 2 children (never 1)
- Complete binary tree — all levels are fully filled except possibly the last, which is filled left to right. Heaps use this shape.
- Perfect binary tree — all interior nodes have 2 children and all leaves are at the same level. A perfect tree of height h has exactly 2^(h+1) - 1 nodes.
Height and balance
The height of a tree determines how long paths are. A balanced tree keeps height close to \(\log_2(n)\), making operations fast. An unbalanced tree can degrade to height n (like a linked list), making traversals slow in terms of stack depth.