All chapters[•]Data StructuresChapter 06
Data Structures · Chapter 6

Sorted Maps and Balanced Search TreesData Structures · Chapter 6

A binary search tree is fast only while it stays balanced, and keys that arrive in sorted order turn it into a chain. This chapter shows three ways to keep a search tree balanced without knowing which keys come next: the AVL tree repairs itself with rotations, the (2,4) tree is balanced by construction because a node may hold several keys, and the red-black tree is a (2,4) tree written with ordinary binary nodes. Then we use such a tree as a sorted map, which answers "the last name before Morgan" and "everyone from M to P" in O(log n).

Instructors: Boxi Yu · Yintong Huo · Python and Java versions (switch at the top) · Every program here has been run, and every output shown is the real output. · All chapters

Insert in sorted order

Press Insert to add the keys 1, 2, 3, … one after another to three trees side by side: a plain search tree grows into a chain, an AVL tree rotates and stays a few levels high, a (2,4) tree splits its nodes and grows only at the top. The heights and the number of rotations and splits are shown after every key.

Why this matters

about 90–120 minutes (4 videos of 8–10 minutes plus the exercises).

A search tree is only as good as its shape

Inserting the keys 1 to 1,000 in order into a plain binary search tree gives a tree of 1,000 levels, and finding the last key takes 1,000 steps; balanced, the same keys need 10 levels. Real data often arrives in order (timestamps, ids), so a guarantee about the height is not a luxury.

One idea, three structures

A rotation changes the shape of a tree without changing the order of its keys; a (2,4) tree stays balanced by letting nodes hold 1 to 3 keys; a red-black tree is the same (2,4) tree drawn with a colour. Seeing that they are the same thing makes the three rules of a red-black tree something you can derive, not memorise.

A map that knows about order

A hash map finds a key instantly but cannot tell you the next smaller key or a range. A balanced tree can: a sorted map adds first, last, floor, ceiling and range queries, all in O(log n). It is what Java's TreeMap and TreeSet are, and what Python's standard library does not have.

5 parts

Four videos with their notes, then the summary and practice. Read them in order.

01

Rotations and AVL trees

A rotation lifts a node above its parent and moves one subtree to the other side; it changes heights but never the order of the keys. The AVL rule says that the balance factor of every node is −1, 0 or +1. After an insertion, walk back up and fix the first node that leans by two with one single or one double rotation. The thinnest AVL trees follow the Fibonacci numbers, so the height is at most about 1.44 log₂ n.

rotationbalance factorAVL rulesingle and double rotationfour casesFibonacci treesO(log n) height
Open →
02

(2,4) trees: split and fuse

Instead of repairing a binary tree, build a tree that cannot become unbalanced: let a node hold one, two or three keys (two, three or four children) and keep every leaf at the same depth. An overfull node splits and pushes its third key up; an empty node borrows with a transfer or merges with a fuse. The tree grows and shrinks only at the root, so its height stays between log₄ n and log₂ n.

multiway search tree2-node, 3-node, 4-nodesplittransferfusesame depth for all leavesO(log n)
Open →
03

Red-black trees as (2,4) trees

A (2,4) tree is balanced by construction, but nodes with a variable number of keys are awkward to store. Colour ordinary binary nodes and the same tree appears: a black node together with its red children is one (2,4) node. The three red-black rules are what a valid (2,4) tree looks like in binary form, an insertion is a split or a re-encoding of a node, and the height is at most 2·log₂(n + 1).

red-black treeblack node and red childrenrecolouringrotationred uncle / black uncleblack height2 log₂ n
Open →
04

Sorted map operations

A hash map finds a key instantly but cannot say who comes next. A sorted map adds first, last, floor, ceiling and range queries to get, put and remove. A balanced search tree answers all of them in O(log n) (plus k for k results); a sorted array answers the queries too, but every insertion shifts half of it.

sorted mapfirst / lastfloor / ceilingsub-map (range query)bisectTreeMapO(log n)
Open →
05

Summary and practice

A one-page map of the chapter, five self-check questions, ten exercises with solutions, and a way to test claims an AI makes about complexity.

self-checkexercises
Open →

How to use these notes

Watch · Predict · Step through · Practise

STEP 1

Watch

Each part starts with its video, 8–10 minutes, in Python or Java.

STEP 2

Predict

Answer the amber Predict box before you open the answer.

STEP 3

Step through

The interactive demos are being added; each one is described where it will appear.

STEP 4

Practise

Finish with the self-check and the exercises, with templates in your language.