15-150: Principles of Functional Programming

Lecture 16: Red-Black Trees

In today's lecture, we discussed red-black trees, a self-balancing binary search tree data structure with invariants that ensure that lookup remains logarithmic in complexity.

In previous lectures, we discussed the SML module system and the importance of abstracting away details and hiding information so that users do not get confused and do not break our invariants. The red-black tree is the perfect data structure for illustrating the importance of opaqueness, as it has clear invariants that must be preserved in order to maintain its performance advantage.

We walked through the invariants of the red-black tree, which is that given that each node is colored either red or black, then there must be an equal number of black nodes on any path from the root to the leaves, and that no red node is allowed to have a red child.

We saw that these invariants could be preserved through insertion by noticing a local invariant violation through pattern-matching, then fixing it by recursively rebalancing upwards until the violation is no longer witnessed. This was then very naturally implemented by a recursive insertion function which rebalanced on the resulting tree.

Slides