Skip to content
Data Structures and Algorithms / Trees, Heaps, and Ordered Search

Overview

Topic 2 closed with a genuine gap: hash tables give expected O(1)O(1) lookup but destroy order (no "give me the next key above this one" query), while a plain sorted array gives ordered traversal but O(n)O(n) insertion. This topic closes that gap with binary search trees (BSTs), which give O(h)O(h) search, insertion, and ordered traversal simultaneously, where hh is the tree's height — then immediately confronts the fact that an adversarially- or unluckily-ordered sequence of insertions can make h=Θ(n)h = \Theta(n), degrading a BST to a linked list. Red-black trees fix this by maintaining a balance invariant via rotations, guaranteeing h=O(log⁡n)h = O(\log n) always. The topic closes with augmentation — the general recipe for extending a balanced tree with extra bookkeeping (rank, interval overlap) without breaking its balance guarantee — and a practical note on when Python's built-in heapq/bisect/dict/set suffice in place of hand-rolled trees.

By the end of this topic you should be able to:

  • implement BST search, insertion, and deletion, and explain why an adversarial insertion order degrades performance;
  • state the red-black properties and explain how rotations restore them after insertion/deletion;
  • describe the augmentation recipe and apply it to build an order-statistics tree and an interval tree;
  • choose, for a given quant task, between a hand-rolled balanced tree and Python's standard-library equivalents.

In this lesson

  1. Contents
  2. The big picture

The full lesson is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or explore the curriculum.