Trees and binary search trees
A tree is a hierarchy: a root node with children, which have children of their own. File systems, HTML pages (the DOM), company org charts, JSON documents and database indexes are all trees. A binary tree gives each node at most two children, and a binary search tree (BST) keeps them ordered so searching is fast.
8 ← root
/ \
3 10 ← children of 8
/ \ \
1 6 14 ← leaves: 1, 4, 7, 13
/ \ /
4 7 13| Term | Meaning |
|---|---|
| Root / leaf | The top node / a node with no children |
| Depth of a node | Edges from the root to it |
| Height of a tree | The depth of its deepest leaf |
| Subtree | A node and all its descendants |
| Balanced | Left and right heights differ little everywhere, so height ≈ log n |
Building a tree and traversing it
These three are depth-first traversals. Breadth-first (level-order) traversal visits the tree level by level, using a queue:
Thinking recursively about trees
Most tree problems follow one shape: solve it for the left subtree, solve it for the right subtree, combine:
Binary search trees
In a BST, for every node: everything in the left subtree is smaller, everything in the right subtree is larger. Searching is like binary search: each comparison discards a whole subtree.
A BST's operations cost O(height). Balanced, that's O(log n); but inserting sorted data builds a "tree" that's really a linked list, height n, and everything becomes O(n). Self-balancing trees fix this by rotating nodes after inserts: AVL trees, red-black trees (Java's TreeMap, C++'s std::map) and B-trees (database indexes, which keep hundreds of keys per node so the tree stays only 3–4 levels deep).
Validating a BST
A favourite interview trap: checking only that each node is bigger than its left child and smaller than its right child is not enough. Every node must fit the range allowed by all its ancestors:
Lowest common ancestor
Tries: trees for strings
A trie (prefix tree) stores strings character by character, so words sharing a prefix share a path. It's what powers autocomplete:
Lookups cost O(length of the word), regardless of how many words are stored.
Practice
- Write
is_balanced(root): every node's subtrees differ in height by at most 1 (do it in one pass). - Find the k-th smallest key in a BST using an in-order traversal.
- Serialise a binary tree to a string and rebuild it.
1.Which traversal visits a BST's keys in sorted order?
2.Why can a BST degrade to O(n) operations?
3.What makes tries good for autocomplete?