Tree-Based Containers

Explore how std::set and std::map maintain order using self-balancing binary trees, and why their design trades hardware speed for safety guarantees.

Ryan McCombe
Published

Over the previous two chapters, we combined hash functions, contiguous open-addressed arrays, and SIMD vectorization; we built hash tables capable of locating a single key among millions in a handful of CPU clock cycles.

Given that kind of raw speed, it is reasonable to ask why we would ever use any other container. If a hash table can insert, delete, and find items in O(1)O(1) constant time, why do tree-based containers with slower O(log N)O(\text{log }N) complexity even exist?

The answer lies in what a hash function destroys: order. To prevent collisions, the avalanche effect of a good hash function deliberately scrambles similar inputs across the entire 64-bit integer spectrum. The keys 100 and 101, or "Alice" and "Alan", are flung to completely unrelated buckets in memory.

For exact key lookups, this chaos is a feature - it reduces primary clustering. However, many real-world engineering problems depend on the natural sequence of our data. For example:

  1. Ordered Iteration: We need to traverse our collection from smallest to largest, such as rendering a sorted leaderboard or processing chronological network packets.
  2. Extreme Queries: We need fast access to the minimum or maximum element in a collection, such as finding the player with the highest score or matching the lowest sell order in a financial exchange.
  3. Range and Proximity Queries: We need to find all elements that fall between two boundaries - such as every database record between 10:00 AM and 10:05 AM - or locate the closest existing key to a target value.

In a hash table, answering a simple range query like "find all keys between 50 and 100" is extremely inefficient. Because those keys could be sitting in any bucket, we have no choice but to execute a brute-force O(N)O(N) linear scan across the backing buffer.

When our algorithms require data to remain sorted while supporting dynamic insertions and removals, we can turn to trees. In this lesson, we will explore what these containers offer, look under the hood at the self-balancing binary trees that power them, and examine the trade-offs between standard node-based trees and contiguous memory layouts.

Trees

Every data structure we have built so far - whether a contiguous std::vector, a ring buffer, or a doubly linked list - has been linear. In a linear layout, elements sit in a single one-dimensional sequence where each item has at most one predecessor and one successor.

Instead of pointing forward and backward along a single chain, nodes in a tree branch downward into multiple sub-paths:

When discussing trees and their nodes, the following terminology is commonly used:

  • Parents and Children: Any node that branches downward is a parent, and the nodes directly connected below it are its children.
  • The Root: The single entry point at the very top of the tree. The root has no parent.
  • Leaves: Nodes at the very bottom of the tree that have no children of their own.
  • Subtree: Any node in the hierarchy, together with all of the descendants branching beneath it, forms a self-contained smaller tree.

Organizing data into a tree changes the mechanics of traversal. In a linear list of NN elements, stepping past one node eliminates only one element from our search. In a tree, stepping from a parent down to one of its children eliminates all of the other child subtrees in a single move.

Branching Factor and Tree Height

The performance of any tree is governed by two measurements: its branching factor and its height.

The branching factor is the maximum number of children any single parent node can have. The most common branching factor is 2 - where every node splits into at most two children. Trees with a branching factor of 2 are called binary trees.

A tree with a higher branching factor - such as 4, 8, or 16 children per node - is called a wide tree or ddary tree, where dd is the variable used to represent the branching factor. "Binary tree" is just another name for a 2-ary tree, whilst 4-ary and 8-ary are examples of wide trees.

The height (or depth) of a tree is the number of levels we must step through to travel from the top Root down to the deepest Leaf.

Branching factor and tree height are inversely related - a wider tree requires fewer levels to store the same quantity of elements. If a tree has a branching factor of dd, then level 0 (the root) holds 11 node, level 1 holds up to dd nodes, level 2 holds up to d2d^2 nodes, and so on.

That exponential fan-out means the height hh required to store NN elements grows logarithmically, with the branching factor dd serving as the base of the logarithm: h≈log d(N)h \approx \text{log }_d(N)

This logarithmic scaling of tree height is what gives most tree-based algorithms their O(log N)O(\text{log }N) performance characteristics. Because most tree operations - searching for a key, inserting a new element, or deleting an existing one - start at the Root and walk downward to a Leaf, the height of the tree directly dictates its algorithmic efficiency:

  • Vertical Hops (Height): In a binary tree (d=2)(d = 2), storing 1,000,0001,000,000 requires a height of log2(1,000,000)≈20\text{log}_2(1,000,000) \approx 20 levels. Walking from the root to a leaf takes at most 20 downward steps.
  • Horizontal Work (Branching Factor): If we widen the branching factor to d=16d = 16, the height drops to log16(1,000,000)≈5\text{log}_{16}(1,000,000) \approx 5 - cutting the number of vertical steps by 75%. In exchange, the CPU must do more horizontal work at each level, comparing up to 16 child branches instead of just 2 to decide which path to take next.

This trade-off between vertical hops and horizontal width is an important decision in our data structure design, and something we'll explore throughout this chapter.

Balanced and Unbalanced Trees

This assumption of logarithmic height and algorithmic efficiency is predicated on an important assumption: that the tree is relatively balanced.

A balanced tree is one that uses most of the horizontal space available to it. For a binary tree, that means that most non-leaf nodes have two children - both a left and right subtree. Naturally, if a tree isn't using most of the horizontal space available to it, it must compensate by being taller if it is to store the same number of elements NN:

If things get extremely unbalanced, our tree begins to look more like a linear sequence of nodes, and therefore inherits the performance characteristics of a linked list. No longer is a walk from the root to a leaf an O(log N)O(\text{log }N) algorithm - it degrades to O(N)O(N):

Let's start by looking at how the standard library implements trees and solves these problems. The standard library provides trees that use the classic binary branching factor of 2.

Standard Library Trees

The C++ standard library provides binary tree implementations of the hash containers we covered previously:

Hash-based (unordered)Tree-based (ordered)
std::unordered_setstd::set
std::unordered_mapstd::map
std::unordered_multisetstd::multiset
std::unordered_multimapstd::multimap

Just like their unordered counterparts, std::set stores unique keys, while std::map stores key-value pairs as a std::pair<const Key, Value>. We also have std::multiset and std::multimap for scenarios where we want to allow duplicate keys.

As before, we'll focus on the set version of these containers, which only store keys. There is no meaningful algorithmic difference between sets, maps, multisets, and multimaps.

All of the algorithmic complexity involves inserting and querying keys. A map just stores some additional data alongside each key, and the multi variations require only small, uninteresting logic changes to accept duplicate keys rather than reject them.

Using std::set

At a surface level, inserting and searching in a std::set looks identical to using a std::unordered_set:

dsa_app/main.cpp

#include <iostream>
#include <set>

int main() {
  std::set<int> HighScores;

  // Insert elements in arbitrary, chaotic order
  HighScores.insert(450);
  HighScores.insert(100);
  HighScores.insert(900);
  HighScores.insert(250);
  HighScores.insert(600);

  if (HighScores.contains(250)) {
    std::cout << "Found 250 in the set\n";
  }

  // Iterating over std::set automatically yields
  // elements in sorted order
  std::cout << "Sorted scores: ";
  for (int score : HighScores) {
    std::cout << score << " ";
  }
}
Found 250 in the set
Sorted scores: 100 250 450 600 900

Notice that even though we inserted our integers in random order, iterating over HighScores accesses them in ascending order. The std::set implementation of a binary tree maintains this sorted invariant automatically on every single insert() and erase() call.

Extreme Queries

Because the elements inside std::set and std::map are permanently ordered, they unlock operations that would be much more expensive in std::unordered_set or our custom flat hash tables.

First, we can instantly inspect the smallest element using begin(), or the largest element using rbegin() - the reverse iterator pointing to the final element:

dsa_app/main.cpp

#include <iostream>
#include <set>

int main() {
  std::set<int> HighScores{450, 100, 900, 250, 600};

  // Dereference the first and last iterators
  std::cout << "Lowest score:  " << *HighScores.begin();
  std::cout << "\nHighest score: " << *HighScores.rbegin();
}
Lowest score:  100
Highest score: 900

Range Queries

Second, we can efficiently query ranges of values even when the exact boundary keys do not exist in the container. We do this using two dedicated member functions:

  • The lower_bound() method: Returns an iterator to the first element that is greater than or equal to >= the target key.
  • The upper_bound() method: Returns an iterator to the first element that is strictly greater than > the target key.

By pairing lower_bound() and upper_bound(), we can carve a range out of the container in O(log N)O(\text{log }N) time and iterate over the matching elements:

dsa_app/main.cpp

#include <iostream>
#include <ranges>
#include <set>

int main() {
  std::set<int> HighScores{450, 100, 900, 250, 600};

  // A view from the first element >= 200 to the first element > 600
  std::ranges::subrange Scores{
    HighScores.lower_bound(200),
    HighScores.upper_bound(600)
  };

  std::cout << "Scores between 200 and 600: ";
  for (int Score : Scores) {
    std::cout << Score << ' ';
  }
}
Scores between 200 and 600: 250 450 600

Insertion and Binary Search Trees

Why do std::set and std::map need a tree structure at all? Why not simply store the elements inside a sorted std::vector?

As we saw in , searching a sorted std::vector with binary search is an O(log N)O(\text{log }N) operation. However, modifying a sorted std::vector is expensive. Inserting a new value near the front of a million-element array requires physically shifting nearly a million existing elements one slot to the right - an O(N)O(N) memory copy that also invalidates all of our pointers.

To achieve O(log N)O(\text{log }N) searches and O(log N)O(\text{log }N) insertions and deletions without shifting contiguous blocks of memory, std::set and std::map return to the node-based architecture we introduced with , arranging pointers into a Binary Search Tree (BST).

Instead of a doubly linked list's linear Prev and Next pointers, each node in a binary search tree holds two child pointers that split the hierarchy into two directions:

  • The Left Pointer: Points to a child node containing a smaller key.
  • The Right Pointer: Points to a child node containing a larger key.

Every node in the tree obeys this ordering rule: all keys in its left subtree are smaller, and all keys in its right subtree are larger.

Because of this layout, searching or inserting into a binary search tree works just like performing a binary search across pointers. We start at the top Root node and compare our target key against the current node's key. If our target is smaller, we follow the Left pointer; if it is larger, we follow the Right pointer:

At every step down the tree, we eliminate half of the remaining subtrees. And when we reach the bottom to insert or delete a node, we simply allocate or free a single node and update its parent's pointer - zero shifting required.

Balancing and Red-Black Trees

A basic binary search tree has one major vulnerability: its shape depends entirely on the order in which keys are inserted and removed.

For example, if we insert keys in a relatively random order, the tree naturally spreads out into a balanced layout with a height of roughly log (N)\text{log }(N).

However, if we insert keys in ascending order - such as 10, 25, 40, 50, 60 - every new number is larger than all previous numbers. Therefore, every node attaches to the right-hand branch:

When fed sorted data, a naive binary search tree degenerates into a linked list, and its O(log N)O(\text{log }N) operations degrade into slow O(N)O(N) linear scans.

The standard mandates that std::set and std::map maintain O(log N)O(\text{log }N) complexity regardless of insertion order, and through the churn of additional elements being added and existing ones being erased.

Standard library implementations ensure this performance is maintained through the full lifetime of the tree by adding a balancing mechanism to the insertion and deletion functions. These self-balancing binary search trees are typically called Red-Black Trees.

Whenever an insertion or deletion makes one branch disproportionately long, a Red-Black Tree repairs its balance by rewiring pointers in an operation called a tree rotation:

Just like splicing a node-based linked list, a tree rotation does not move the nodes in physical memory - it simply updates three pointers to modify the logical flow of the tree.

Why the Standard Library Uses Node-Based Trees

Before we examine the hardware bottlenecks of std::set and std::map, it is important to understand why the standard library designed them this way. Just like std::unordered_set and std::unordered_map, the standard ordered containers prioritize safety and predictability guarantees:

No Reallocation Spikes

Contiguous containers like std::vector and flat hash tables occasionally hit capacity and must allocate a new buffer, copying or rehashing every element at once. A Red-Black tree allocates one node at a time and rebalances locally in O(log N)O(\text{log }N) steps, providing predictable latency on every single insertion.

Pointer and Iterator Stability

Because insertions, deletions, and tree rotations only rewire pointers between nodes, the nodes themselves never move in physical RAM.

As long as an element remains in a std::set or std::map, any raw pointer, reference, or iterator pointing to it is guaranteed to remain valid, even as thousands of other elements are inserted or removed around it:

dsa_app/main.cpp

#include <iostream>
#include <set>

int main() {
  std::set<int> Scores{50};

  // Grab a raw pointer to the element inside the set
  const int* PtrTo50{&(*Scores.find(50))};
  std::cout << "Address before inserts: " << PtrTo50
    << " (Value: " << *PtrTo50 << ")\n";

  // Insert thousands of elements, triggering numerous
  // Red-Black tree rotations and rebalancing steps
  for (int i{0}; i < 10'000; ++i) {
    Scores.insert(i);
  }

  // The node containing 50 never moved in physical RAM
  std::cout << "Address after inserts:  " << PtrTo50
    << " (Value: " << *PtrTo50 << ")";
}
Address before inserts: 0x55d4a2b19eb0 (Value: 50)
Address after inserts:  0x55d4a2b19eb0 (Value: 50)

When we are building a general-purpose application where external systems hold long-lived pointers or iterators into a dynamic, sorted collection, std::set and std::map provide a foolproof safety net.

The Hardware Limitations of Pointer Trees

When we don't need strict pointer stability, however, we pay a massive hardware tax for how std::set and std::map operate on silicon. We have the familiar costs we covered previously when working with other node-based containers like std::list and std::unordered_set, but also a new penalty that is specific to tree-based storage.

The Familiar Costs of Node-Based Storage

Because every element in a std::set or std::map is an individually heap-allocated node, these containers suffer from the same physical memory problems we covered when introducing linked lists.

First, we have the same structural memory bloat. To store a single 4-byte int, each Red-Black tree node must also store three 8-byte pointers (Parent, Left, Right), a 4-byte color/alignment field, and a 16-byte heap allocator header. We spend 48 bytes of RAM to store a 4-byte integer - over 90% overhead.

Secondly, we also have pointer chasing and cache misses. Because nodes are allocated on the heap at different times and continuously reshuffled by tree rotations, logically adjacent parent and child nodes can be far apart in physical memory.

Just like traversing a std::list, every hop down a large std::set forces the CPU to wait on a dependent pointer load from main memory, completely defeating the hardware prefetcher.

The Tree-Specific Penalty: 50/50 Branch Mispredictions

On top of the pointer-chasing stalls it shares with linked lists, a binary search tree introduces a second hardware penalty: branch mispredictions.

When traversing a linked list (Current = Current->Next), there is no conditional decision to make. When traversing a binary search tree, every single node forces the CPU to evaluate a data-dependent if statement:

// Which pointer do we chase next?
if (targetKey < Current->Key) {
  Current = Current->Left;
} else {
  Current = Current->Right;
}

As we , the CPU's branch predictor tries to guess which way an if statement will go before the comparison finishes, keeping the instruction pipeline full.

Branch predictors are great at learning repeating patterns. In a for loop that runs 1,000 times, the branch predictor guesses "keep looping" with 99.9% accuracy.

But in a balanced binary search tree, every node is specifically arranged to split the remaining keys into two halves. That means for arbitrary queries, the probability of branching left versus right at any node is 50/50.

A 50/50 branch is a random coin flip - impossible to predict accurately. On roughly half of the steps down the tree, the CPU guesses the wrong direction, has to flush its execution pipeline, and pays a misprediction penalty on top of the cache miss.

Benchmarking std::set vs Sorted std::vector

When we need an ordered collection for a read-heavy workload and don't require pointer stability, our baseline contiguous alternative is a sorted std::vector (or C++23's std::flat_set adapter) queried with std::ranges::lower_bound().

Both std::set::find() and std::ranges::lower_bound() on a sorted vector are O(log N)O(\text{log }N) binary searches that perform the same number of key comparisons. Let's benchmark them head-to-head across growing dataset sizes - from 64 elements up to 1,048,576 elements - to measure the true cost of node bloat and pointer chasing:

benchmarks/main.cpp

#include <benchmark/benchmark.h>
#include <set>
#include <vector>
#include <algorithm>
#include <random>
#include <numeric>

std::vector<int> GenerateData(int n) {
  std::vector<int> data(n);
  std::iota(data.begin(), data.end(), 1);
  std::mt19937 rng{42};
  std::shuffle(data.begin(), data.end(), rng);
  return data;
}

std::vector<int> GenerateQueries(int n) {
  std::vector<int> queries(1000);
  std::mt19937 rng{1337};
  std::uniform_int_distribution<int> dist{1, n};
  for (int& q : queries) q = dist(rng);
  return queries;
}

static void BM_StdSet_Find(benchmark::State& state) {
  int n{static_cast<int>(state.range(0))};
  auto data{GenerateData(n)};
  auto queries{GenerateQueries(n)};

  std::set<int> set(data.begin(), data.end());

  for (auto _ : state) {
    for (int q : queries) {
      benchmark::DoNotOptimize(set.find(q));
    }
  }
}

static void BM_SortedVector_Find(benchmark::State& state) {
  int n{static_cast<int>(state.range(0))};
  auto vec{GenerateData(n)};
  std::ranges::sort(vec);
  auto queries{GenerateQueries(n)};

  for (auto _ : state) {
    for (int q : queries) {
      benchmark::DoNotOptimize(
        std::ranges::lower_bound(vec, q)
      );
    }
  }
}

#define REGISTER_BENCHMARK(fn)                \
  BENCHMARK(fn)                               \
      ->RangeMultiplier(16)                   \
      ->Range(1 << 16, 1 << 22)               \
      ->Unit(benchmark::kMicrosecond)

REGISTER_BENCHMARK(BM_StdSet_Find);
REGISTER_BENCHMARK(BM_SortedVector_Find);
--------------------------------------
Benchmark                          CPU
--------------------------------------
BM_StdSet_Find/65536            120 us
BM_StdSet_Find/1048576          261 us
BM_StdSet_Find/4194304          399 us

BM_SortedVector_Find/65536     80.2 us
BM_SortedVector_Find/1048576    160 us
BM_SortedVector_Find/4194304    262 us

Even though both algorithms execute log N\text{log }N steps, searching a sorted std::vector is notably faster than std::set in these tests:

  • 12x Smaller Footprint: At 1,048,576 elements, the std::vector<int> is only 4 MB, fitting comfortably inside the CPU's L3 cache. The std::set<int> consumes 48 MB of scattered heap memory, spilling out into main RAM on most systems.
  • Cache-Line Convergence: In a std::vector<int>, once the final 4 steps of the binary search narrow the range down to 16 elements (64 bytes), all remaining comparisons happen inside a single cache line.

However, a sorted std::vector still has O(N)O(N) insertion costs, and even binary search on a large sorted array jumps erratically across distant cache lines. During its early steps, it might follow a path like N/2N/2 to N/4N/4 to N/8N/8. When NN is large, these jumps are also large.

Throughout the rest of this course, we will discover alternative techniques to solve these problems without the performance overhead. We will first learn how to flatten trees directly into contiguous arrays using implicit index math - starting in the next lesson with the priority heap.

Summary

To wrap up our introduction to tree-based containers:

  1. Order vs Hashing: While hash tables provide O(1)O(1) exact lookups, hash functions scramble key order. When we need sorted iteration, min/max access, proximity, or range queries, we need an ordered container.
  2. Binary Search Trees and Red-Black Balancing: To avoid the O(N)O(N) memory shifts of inserting into a sorted array, std::set and std::map link heap-allocated nodes into a binary search tree, using Red-Black tree rotations to keep the hierarchy balanced at O(log N)O(\text{log }N) height.
  3. Standard Library Guarantees: The node-based design of std::set and std::map avoids reallocation spikes and guarantees strict pointer and iterator stability across insertions and removals.
  4. The Hardware Cost: When we don't need pointer stability, std::set and std::map suffer from severe hardware penalties: 48-byte node bloat per 4-byte integer, cache-thrashing pointer chases across the heap, and unpredictable 50/50 branches at every node that stall the CPU pipeline.
Next Lesson
Lesson 78 of 78

Implicit Binary Trees and Priority Heaps

Learn how to map a binary tree directly onto a contiguous std::vector using integer arithmetic to build a fast Priority Heap.

Have a question about this lesson?
Answers are generated by AI models and may not be accurate