Algorithms Made Simple

Binary Search Trees: Why Balance Is the Whole Story

The ordering rule that makes lookups fast, how sorted input can wreck it, and how self-balancing trees fix it.

Algorithms Made Simple · 5 min read

A binary search tree keeps data in an order that makes lookups fast, as long as the tree stays reasonably balanced. Balance is the whole story.

The ordering rule

In a binary search tree, each node has at most two children. Everything in its left subtree is smaller than the node, and everything in its right subtree is larger. To find a value, compare it with the current node and go left or right. Each comparison discards a whole side of the tree.

Why shape matters

If the tree is balanced, its height is about log base 2 of n. A million items need about 20 comparisons to find any one. But if you insert items that are already sorted, each new item goes to the right of the last, and the tree becomes a chain. Then a lookup may walk all one million nodes.

Same data, same rules, very different speed. The difference is only the shape.

Self-balancing trees

Structures such as AVL trees and red-black trees rearrange a few nodes after an insertion or deletion, using small moves called rotations, so the height stays proportional to log n. You pay a little extra work on each update to keep every lookup fast.

A bonus property

Walking a binary search tree in order, left subtree then node then right subtree, visits values from smallest to largest. That makes it easy to list items in sorted order or to find everything in a range.

When to use one

Use an ordered tree when you need sorted order, nearest-value queries or range queries along with fast updates. If you only need exact-match lookups, a hash table is usually simpler and faster.

More guides from this book