AlgoViz

Binary search tree

medium 18 min

A binary search tree keeps every key in order: for each node, all keys in its left subtree are smaller and all keys in its right subtree are larger.

Where it shows up

The same pattern appears across everyday software.

  • Database and file system indexes

    Databases index columns with B-trees and B+ trees, the many-keys-per-node cousins of the BST, so a lookup among millions of rows touches only a handful of disk pages. File systems such as NTFS, HFS+, Btrfs and ext4's directory index use the same family of trees.

  • Ordered maps and sets in standard libraries

    Java's TreeMap and TreeSet and C++'s std::map and std::set are red-black trees. They give sorted iteration, floor and ceiling lookups and range views in O(log n), which a hash map cannot.

  • Dictionaries and symbol tables

    Compilers and interpreters keep symbol tables of identifiers, and spell checkers and autocomplete keep word lists. When the names must also be listed alphabetically or searched by prefix range, an ordered tree is the natural fit.

  • Leaderboards and ranking

    A game leaderboard inserts scores as they arrive and must always show the top scores and a player's neighbours. A balanced BST (often augmented with subtree sizes to get a rank in O(log n)) or a skip list, as in Redis sorted sets, does this without re-sorting.

  • Scheduling and event queues

    Linux's Completely Fair Scheduler keeps runnable tasks in a red-black tree ordered by virtual runtime and always runs the leftmost task. Timers and event simulators use ordered trees the same way to find the next event.

  • Interval and range lookups

    Augmented BSTs such as interval trees answer questions like which meetings overlap 2pm to 3pm or which IP ranges contain this address. They are built on the same left-smaller, right-larger rule with extra data in each node.