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.

Ryan McCombe
Published

In the previous lesson, we looked under the hood of the standard library's ordered containers, std::set and std::map. To keep elements sorted while supporting O(log N)O(\text{log }N) insertions and removals, these containers link individually allocated heap nodes into a self-balancing binary search tree.

We also saw the hardware cost of that design. Storing a single 4-byte integer inside a std::set consumes 48 bytes of memory, scatters nodes across distant RAM pages, and stalls the CPU with pointer chasing and unpredictable 50/50 branches.

In this lesson, we are going to build a tree that lives entirely inside a single, contiguous std::vector without allocating nodes or storing a single pointer. To do this, we will explore the Priority Queue access pattern and build an implicit binary tree known as a Binary Heap.

The Priority Queue Use Case

Why do std::set and std::map require such a complex node-based structure? Because they guarantee that every single element in the container is kept in strict sorted order at all times.

However, many real-world systems do not actually need the entire collection sorted. Often, we only care about the next item we need to process - the minimum or maximum value currently in the collection.

For example, imagine we are building an event scheduler for a game engine or network server. Thousands of tasks are queued up to execute at specific future timestamps:

  • An explosion sound effect triggers at t = 450.
  • A physics collision resolves at t = 120.
  • A network heartbeat packet sends at t = 800.
  • An AI pathfinding update runs at t = 250.

We cannot use a basic here. Queues access elements based on their insertion order - first in, first out - but we have a different desire here. We want to access elements based on their value. An event scheduled for t = 120 might be inserted long after an event scheduled for t = 800, yet it must execute first, because 120 < 800.

Notice how our engine interacts with this schedule on each frame. It never iterates through all 10,000 future events, and it never asks for the 500th earliest event. It only ever performs two operations:

  1. Insert a new event into the schedule when something happens in the simulation.
  2. Inspect and remove the earliest event when the clock reaches that timestamp.

A container designed for this pattern is called a priority queue.

If we use a sorted std::vector to power a priority queue, inserting a new event requires an O(N)O(N) memory shift just to keep the middle of the array sorted - even though we never read the middle of the array.

If we use std::set or std::multiset, we pay for heap allocations and pointer chasing on every insertion and removal.

Instead, we can avoid both problems by relaxing how strictly we order our tree.

The Heap Invariant

In a binary search tree, every node enforces a strict left-to-right ordering rule: all keys in the left subtree must be smaller than the parent, and all keys in the right subtree must be larger.

In a binary heap, we drop the distinction between left and right children entirely. Instead, we enforce one simple vertical rule called the heap invariant.

Depending on whether we want fast access to the smallest or largest element, heaps come in two variations:

  • Min-Heap: Every parent node must be less than or equal to <= both of its children.
  • Max-Heap: Every parent node must be greater than or equal to >= both of its children.

We will build a min-heap in this lesson, but both variations work identically - the only difference is simply flipping the < and > comparison operators.

Because every parent in a min-heap is smaller than or equal to its children, and those children are smaller than or equal to their children, the smallest element in the entire container is guaranteed to sit at the top Root node.

Even better, because left and right subtrees have no ordering rule relative to each other, we never have to worry about any left/right imbalance. We can keep every level of our tree packed tightly from top to bottom and left to right.

Implicit Binary Trees

When a binary tree is always filled tightly from top to bottom, and from left to right within each level, we don't need pointers to connect parents to children.

Imagine reading the nodes of a tightly packed binary tree level by level, and placing them sequentially into a standard std::vector:

  • Level 0 (The Root): Sits at array index 0.
  • Level 1 (Root's 2 children): Sit at array indices 1 and 2.
  • Level 2 (Their 4 children): Sit at array indices 3, 4, 5, and 6.
  • Level 3 (Their 8 children): Sit at array indices 7 through 14.

Here is an example of a binary tree that follows this layout, and also implements the min heap invariant Parent <= Children:

Because there are never any empty gaps between elements in the array, a predictable mathematical pattern emerges that can help us traverse this tree. For any node sitting at array index i:

  • The Parent always sits at index (i - 1) / 2 given that integer division truncates any remainder.
  • The Left Child always sits at index (2 * i) + 1
  • The Right Child always sits at index (2 * i) + 2

You can click any of the nodes in the following tree to confirm that this arithmetic works:

We call this layout an implicit binary tree. The parent-child links are not stored in memory at all - they are implied purely by an element's index in the array.

By replacing 64-bit pointers with index arithmetic, we solve the major hardware bottlenecks of node-based trees:

  1. Zero Pointer Overhead: We eliminate 24 bytes of Parent, Left, and Right pointers and 16 bytes of heap allocator metadata per element. Every byte in our std::vector<int> is pure payload data.
  2. Fast ALU Navigation: Instead of stalling the CPU to chase a pointer into main memory, finding a child or parent compiles down to a single-cycle bit-shift and addition inside the CPU's registers.
  3. Cache Locality: Because a hardware cache line is 64 bytes, the first cache line of our std::vector<int> holds 16 four-byte integers (indices 0 through 15). That single cache line holds the entire top four levels of the tree, keeping the most frequently visited nodes hot in the L1 cache.

Building the MinHeap Skeleton

Let's start creating our MinHeap class. We will store our elements in a std::vector<int> named Buffer, and define three private helper methods for our index math.

Because the minimum element always sits at the root - Buffer[0] - we can also immediately implement Top():

dsa_core/include/dsa/MinHeap.h

#pragma once
#include <vector>
#include <cstddef>
#include <utility>

class MinHeap {
private:
  std::vector<int> Buffer;

  // Navigate the tree using integer arithmetic
  size_t Parent(size_t i) const {
    return (i - 1) / 2;
  }

  size_t LeftChild(size_t i) const {
    return (2 * i) + 1;
  }

  size_t RightChild(size_t i) const {
    return (2 * i) + 2;
  }

public:
  MinHeap() = default;

  void Reserve(size_t capacity) {
    Buffer.reserve(capacity);
  }

  // The smallest element always sits at index 0
  int Top() const {
    return Buffer[0];
  }

  size_t Size() const {
    return Buffer.size();
  }

  bool Empty() const {
    return Buffer.empty();
  }
};

Inserting Elements

Now let's implement Push() to add a new value to our MinHeap. To keep our index formulas working, our underlying std::vector can never have empty gaps in the middle. That means whenever we insert a new value, there is only one place we can initially put it: the very end of the array using Buffer.push_back().

In our logical tree, appending to the end of the vector attaches the new element as the next leaf on the bottom level.

However, if we insert a small number like 15, placing it at the bottom of the tree might violate the min-heap invariant if its parent is a larger number like 40.

To repair the tree, we execute a helper function called SiftUp():

  1. We start at the newly inserted leaf at the back of the array (Index = Buffer.size() - 1).
  2. We find its parent's index using Parent(Index).
  3. If our element is smaller than its parent, we swap them using std::swap() so the smaller value moves up a level.
  4. We update Index to the parent's slot and repeat the loop until our element encounters a parent that is already smaller than or equal to it, or until it reaches the root at index 0.

We know that a packed binary tree of NN elements has a height of log2(N)\text{log}_2(N), therefore SiftUp() performs at most log2(N)\text{log}_2(N) swaps. This makes Push() an O(log N)O(\text{log }N) operation.

Let's add SiftUp() and Push() to our MinHeap:

dsa_core/include/dsa/MinHeap.h

// ...
class MinHeap {
private:
  std::vector<int> Buffer;

size_t Parent(size_t i) const {/*...*/} void SiftUp(size_t Index) { while (Index > 0) { size_t ParentIdx{Parent(Index)}; // If the parent is already <= our element, // the Min-Heap invariant is satisfied if (Buffer[ParentIdx] <= Buffer[Index]) { break; } // Swap with the larger parent and move up std::swap(Buffer[ParentIdx], Buffer[Index]); Index = ParentIdx; } } public: // ... void Push(int val) { // Append to the back and bubble up into position Buffer.push_back(val); SiftUp(Buffer.size() - 1); } // ... };

Removing the Minimum

Next, we need to implement Pop() to remove the minimum element sitting at Buffer[0].

We cannot simply erase Buffer[0] from the front of our std::vector. Erasing index 0 would force the CPU to shift every remaining element in the array one slot to the left - a slow O(N)O(N) operation that would also scramble every node's parent-child index math.

Instead, we can use the we covered earlier in the course:

  1. We overwrite the root at Buffer[0] with the very last leaf element at Buffer.back().
  2. We call Buffer.pop_back() to remove the duplicate back slot in O(1)O(1) time.

Our vector remains completely contiguous with zero shifting, but the element we just moved from the bottom of the tree to Buffer[0] is almost certainly a large number that violates the min-heap invariant.

To push this large value down to where it belongs, we write a SiftDown() helper function:

  1. Calculate child indices: Starting at Index = 0, we find Left = LeftChild(Index) and Right = RightChild(Index).
  2. Find the smallest value: We compare our current element against its left and right children, checking < Buffer.size() first to make sure those children actually exist in the array.
  3. Swap with the smaller child: If one or both children are smaller than our element, we swap our element with the smaller of the two children. Promoting the smaller child ensures the new parent is smaller than both branches below it.
  4. Repeat: We update Index to the child's slot and repeat the loop until our element is smaller than or equal to both of its children, or until it reaches a leaf at the bottom of the tree.

Let's add SiftDown() and Pop() to our MinHeap:

dsa_core/include/dsa/MinHeap.h

// ...
class MinHeap {
private:
  // ...
  void SiftDown(size_t Index) {
    size_t Count{Buffer.size()};

    while (true) {
      size_t Left{LeftChild(Index)};
      size_t Right{RightChild(Index)};
      size_t Smallest{Index};

      // Check if the left child exists and is smaller
      if (
        Left < Count &&
        Buffer[Left] < Buffer[Smallest]
      ) {
        Smallest = Left;
      }

      // Check if the right child exists and is even smaller
      if (
        Right < Count &&
        Buffer[Right] < Buffer[Smallest]
      ) {
        Smallest = Right;
      }

      // If neither child is smaller, we are done
      if (Smallest == Index) {
        break;
      }

      std::swap(Buffer[Index], Buffer[Smallest]);
      Index = Smallest;
    }
  }

public:
  // ...
  void Pop() {
    if (Buffer.empty()) return;

    // Move the last leaf to the root and shrink the vector
    Buffer[0] = Buffer.back();
    Buffer.pop_back();

    // Sift the new root down into its proper place
    if (!Buffer.empty()) {
      SiftDown(0);
    }
  }
  // ...
};

Let's test our completed MinHeap in main.cpp by pushing unsorted event timestamps and popping them one by one:

dsa_app/main.cpp

#include <iostream>
#include <dsa/MinHeap.h>

int main() {
  MinHeap Scheduler;

  Scheduler.Push(450);
  Scheduler.Push(120);
  Scheduler.Push(800);
  Scheduler.Push(250);
  Scheduler.Push(90);

  std::cout << "Earliest event: " << Scheduler.Top() << "\n";

  std::cout << "Executing events: ";
  while (!Scheduler.Empty()) {
    std::cout << Scheduler.Top() << " ";
    Scheduler.Pop();
  }
}
Earliest event: 90
Executing events: 90 120 250 450 800

Standard Library Support with std::priority_queue

The C++ standard library provides a built-in container adapter that uses this exact implicit binary heap architecture: std::priority_queue, located in the <queue> header.

By default, std::priority_queue wraps a std::vector and configures itself as a max-heap, placing the largest element at top(). To configure it as a min-heap like our MinHeap class, we can pass std::greater<T> as the third template parameter:

dsa_app/main.cpp

#include <iostream>
#include <queue>
#include <vector>
#include <functional>

int main() {
  // Configure std::priority_queue as a Min-Heap
  std::priority_queue<
    int, // The type of elements in the queue
    std::vector<int>, // The underlying container type to wrap
    std::greater<int> // The comparison function for ordering
  > Scheduler;

  Scheduler.push(450);
  Scheduler.push(120);
  Scheduler.push(800);
  Scheduler.push(250);

  std::cout << "Earliest event: " << Scheduler.top() << "\n";

  std::cout << "Executing events: ";
  while (!Scheduler.empty()) {
    std::cout << Scheduler.top() << " ";
    Scheduler.pop();
  }
}
Earliest event: 120
Executing events: 120 250 450 800

Benchmarking

Let's benchmark our contiguous MinHeap and std::priority_queue against std::multiset<int>, a node-based Red-Black tree.

We will simulate an event scheduler managing 200,000 active events, running 100,000 scheduling ticks where each tick extracts the earliest event and pushes a new future event:

benchmarks/main.cpp

#include <benchmark/benchmark.h>
#include <set>
#include <queue>
#include <vector>
#include <random>
#include <functional>
#include <dsa/MinHeap.h>

constexpr int kNumEvents{200'000};
constexpr int kTicks{100'000};

std::vector<int> GenerateData(int count, int seed) {
  std::vector<int> data(count);
  std::mt19937 rng{static_cast<unsigned int>(seed)};
  std::uniform_int_distribution<int> dist{1, 10'000'000};
  for (int& val : data) val = dist(rng);
  return data;
}

const std::vector<int> InitialEvents{
  GenerateData(kNumEvents, 42)
};
const std::vector<int> NewEvents{
  GenerateData(kTicks, 1337)
};

static void BM_StdMultiset(benchmark::State& state) {
  for (auto _ : state) {
    std::multiset<int> set(
      InitialEvents.begin(), InitialEvents.end()
    );

    for (int i{0}; i < kTicks; ++i) {
      benchmark::DoNotOptimize(*set.begin());
      set.erase(set.begin());
      set.insert(NewEvents[i]);
    }
  }
}

static void BM_StdPriorityQueue(benchmark::State& state) {
  for (auto _ : state) {
    std::priority_queue<
      int,
      std::vector<int>,
      std::greater<int>
    > pq(InitialEvents.begin(), InitialEvents.end());

    for (int i{0}; i < kTicks; ++i) {
      benchmark::DoNotOptimize(pq.top());
      pq.pop();
      pq.push(NewEvents[i]);
    }
  }
}

static void BM_CustomMinHeap(benchmark::State& state) {
  for (auto _ : state) {
    MinHeap heap;
    heap.Reserve(kNumEvents);
    for (int val : InitialEvents) heap.Push(val);

    for (int i{0}; i < kTicks; ++i) {
      benchmark::DoNotOptimize(heap.Top());
      heap.Pop();
      heap.Push(NewEvents[i]);
    }
  }
}

BENCHMARK(BM_StdMultiset)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_StdPriorityQueue)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_CustomMinHeap)->Unit(benchmark::kMillisecond);
------------------------------
Benchmark                  CPU
------------------------------
BM_StdMultiset         96.4 ms
BM_StdPriorityQueue    7.71 ms
BM_CustomMinHeap       13.4 ms

Even though std::multiset and MinHeap are both O(log N)O(\text{log }N) trees, our binary heap is already 7x faster in these tests. The std::priority_queue implementation - a more optimized form of the same core idea - expands the lead even further.

However, there is still has plenty of room for improvements. When SiftDown() jumps from index i to 2 * i + 1 in a large heap, the CPU fetches an entire 64-byte cache line (16 four-byte integers), inspects only 2 children, and ignores the other 14 integers in that cache line.

In the next lesson, we will optimize our implicit heap for hardware cache lines. We will build d-ary heaps, packing 2, 4, 8 or 16 children side-by-side to outperform std::priority_queue.

Complete Code

Here is the complete implementation of our implicit MinHeap:

Files

dsa_core
dsa_app
Select a file to view its content

Summary

In this lesson, we eliminated node pointers by mapping a binary tree directly onto a contiguous array:

  1. The Priority Queue Pattern: When a system only needs to insert items and extract the current minimum or maximum element - Top() - maintaining a fully sorted container is unnecessary overhead.
  2. The Heap Invariant: Instead of ordering left and right subtrees, a min-heap only requires that every parent is <= its children. This guarantees the global minimum always sits at the root - Buffer[0] - without needing tree rotations.
  3. Implicit Array Indexing: By storing nodes level by level inside a std::vector, we replace 24 bytes of pointers per node with fast integer math to find the LeftChild(), RightChild(), or Parent() of any node.
  4. Sifting and Swap-and-Pop: Push() appends new elements to the back of the vector and bubbles them upward via SiftUp(). Pop() overwrites Buffer[0] with Buffer.back() then restores the heap invariant via SiftDown().
Have a question about this lesson?
Answers are generated by AI models and may not be accurate