Data structures and algorithms path · Finding things · Topic 8 of 13

Trees, binary search trees and balance

Not started

A tree is a set of nodes where each node has one parent (except the root) and any number of children. A binary search tree (BST) adds one rule: everything in a node's left subtree is smaller than it and everything in its right subtree is larger. That rule turns lookups into a walk down a single path, so the cost is the height of the tree, which is O(log n) if the tree is balanced and O(n) if it isn't.

Why it matters: Sorted maps, database indexes, file systems and the DOM are trees; whether they stay balanced decides whether a lookup takes 30 steps or 30 million.

  1. 1The BST rule

    Every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is larger.

  2. 2Cost is the height

    Search, insert and delete walk one path from the root, so they cost O(height). In-order traversal visits keys in sorted order.

  3. 3Sorted input breaks a naive tree

    Inserting keys in order builds a tree that is one long path, so every operation becomes O(n).

  4. 4Balanced trees fix it

    Red-black and AVL trees rebalance with rotations to keep the height O(log n); B-trees keep many keys per node for disks.

1

How it works

The explanation, with examples you can run.

Search, insert and sorted order

To find a key, start at the root and go left if the key is smaller, right if it is larger, until you find it or fall off the tree. Inserting is the same walk, attaching a new node where you fell off. Visiting the left subtree, then the node, then the right subtree gives every key in ascending order, which is what a hash table can't do:

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Because keys are ordered, a BST also answers range queries ("all keys between 30 and 60"), the smallest or largest key, and "the next key after x", each in O(height) plus the size of the answer.

Why balance matters

A plain BST's shape depends entirely on the order of insertion. Random order gives a bushy tree of height a small multiple of log n. Sorted order, which is very common in practice (timestamps, auto-increment ids), gives a single path:

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Building the sorted tree took about 50 million comparisons (0 + 1 + … + 9,999); in the shuffled tree no insert needed more than 29.

Balanced trees, at a high level

Self-balancing trees do a little extra work on each insert and delete to keep the height O(log n) whatever the order:

  • AVL trees keep the heights of every node's two subtrees within one of each other, restoring that with rotations, small local re-wirings that preserve the BST order.
  • Red-black trees colour nodes and enforce rules that keep the longest path at most twice the shortest. They rebalance less often than AVL trees. Java's TreeMap is one (its docs promise log(n) time for get, put and remove), and C++'s std::map is usually implemented as one.
  • B-trees (and B+ trees) give each node hundreds of keys and children, sized to a disk page. With that much branching a table of millions of rows is only 3 or 4 levels deep, so a lookup reads only 3 or 4 pages. That is the default index type in PostgreSQL, MySQL's InnoDB and SQLite.

You will rarely implement one of these yourself. What matters is knowing that an ordered map gives you O(log n) operations plus ordering, a hash map gives you O(1) average without ordering, and an unbalanced tree gives you neither guarantee.

2

Check yourself

3 questions. Get them all right to finish this topic.

  1. 1.You insert 1, 2, 3, …, 10,000 in that order into a plain (unbalanced) binary search tree. What is its height?
  2. 2.What does an in-order traversal (left subtree, node, right subtree) of a BST produce?
  3. 3.Why do databases use B-trees for indexes rather than binary trees?

0 of 3 right so far. Get all three to finish this topic.