BST / Ordered Set

Binary search trees and the ordered sets built on them: search, insert and delete along one path, floor and ceiling queries, and the calendar-style problems they solve.

Overview

A binary search tree (BST) is a binary tree with one 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. The rule covers whole subtrees, not just the two children. Because of it, search, insert and delete all follow a single path from the root, and an inorder traversal lists the keys in sorted order.

An ordered set or ordered map (Java's TreeSet and TreeMap, C++'s std::set and std::map) is a self-balancing BST behind a library interface: Java documents a red-black tree, and C++ requires logarithmic search, insert and removal, which its standard libraries usually meet with a red-black tree. You reach for one whenever you need a collection that stays sorted while items come and go: the nearest value above or below a key, all keys in a range, or the next free slot in a calendar.

This chapter walks one small tree through search, insert and delete, then shows why balance decides the cost, and ends with the questions that only a sorted structure answers cheaply.

The rule and the sample tree

Every example in this chapter uses the tree below.

The rule lets you read several facts straight off this tree. Its inorder traversal is 2, 4, 6, 8, 10, 12, 14, already sorted. The smallest key, 2, is the leftmost node, and the largest key, 14, is the rightmost. The height is 2 edges, which is about log2(7).

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio