Skip to content
Data structures

What is the difference between a heap and a binary search tree

The difference between a heap and a binary search tree comes down to what order each one promises. This essay walks through the invariants, a worked example with a million elements, and a simple rule for choosing between them.

The difference between a heap and a binary search tree is what each one promises about order. A heap guarantees only that every parent beats its children, so the best element always sits at the root. A BST guarantees that everything on the left is smaller and everything on the right is larger, so it supports search and sorted traversal.

Both are drawn as binary trees, both usually give you logarithmic insertion, and both show up in the same chapter of every textbook. That surface similarity is why people confuse them. Underneath, they are built for different questions. One answers "what is next?" The other answers "where is this exact thing, and what sits around it?" I will try to make that distinction concrete enough that you never have to memorise it again.

What does each structure actually guarantee?

A heap guarantees a partial order: in a min-heap, each node is less than or equal to its children, and nothing is promised between siblings or cousins. A BST guarantees a total order: for every node, all keys in its left subtree are smaller and all keys in its right subtree are larger. That one-sided versus two-sided rule explains nearly every other difference.

Here is an analogy I use. A heap is a triage board in an emergency room. The nurse at the front desk knows exactly who must be seen next, and when that patient leaves, the board reshuffles just enough to surface the next most urgent case. Ask the board whether a patient named Okafor is waiting and it has no idea; you would have to read every card. A BST is a phone directory. Finding Okafor takes a few page flips, and the people next to Okafor are the alphabetical neighbours. But ask the directory who is the most urgent case in the building and it shrugs, because its ordering is about names, not priority. Each structure is excellent at the one question it was organised around, and mediocre at the other.

The shape rules differ too. A heap is a complete binary tree: every level is full except possibly the last, and the last level fills left to right. That shape is not decoration. It is what lets a heap live in a flat array with no pointers at all. A BST has no shape rule. Its shape is whatever your insertion order produces, which is both its flexibility and its main hazard.

Take the sequence 7, 3, 9, 1, 5 and insert it into both. For the min-heap, you append each value at the next free slot and swap upward while it is smaller than its parent. Inserting 7 gives [7]. Inserting 3 gives [7, 3], then a swap gives [3, 7]. Inserting 9 gives [3, 7, 9]. Inserting 1 appends at index 3, swaps with its parent 7 at index 1, then swaps with 3 at the root, giving [1, 3, 9, 7]. Inserting 5 appends at index 4, and its parent is 3, so it stays: [1, 3, 9, 7, 5]. Notice that 9 sits before 7 and 5 in the array, even though it is the largest. The heap does not care.

For the BST, 7 is the root, 3 goes left, 9 goes right, 1 goes left of 3, and 5 goes right of 3. An in-order walk returns 1, 3, 5, 7, 9, fully sorted. Finding 5 takes three comparisons (7, then 3, then 5). In the heap, finding 5 means scanning the array until you hit it. With five elements that is nothing; with a million it is the whole story.

How do the two compare on real operations?

A heap wins on reading the extreme and on building from scratch; a balanced BST wins on arbitrary lookup, ordered traversal, and neighbour queries. Both insert in O(log n) when the BST is balanced. The table puts the costs side by side, assuming a self-balancing BST such as a red-black tree.

OperationBinary heapBalanced BSTPlain BST (worst case)
Peek min or maxO(1)O(log n), or O(1) with a cached pointerO(n)
InsertO(log n) worst, O(1) averageO(log n)O(n)
Remove the extremeO(log n)O(log n)O(n)
Find an arbitrary keyO(n)O(log n)O(n)
Delete an arbitrary keyO(n) to find, then O(log n)O(log n)O(n)
Sorted traversalO(n log n) by repeated extractionO(n) in-orderO(n)
Build from n itemsO(n) with heapifyO(n log n)O(n^2) on sorted input
Successor or range queryNot supportedO(log n) plus output sizeO(n)

Two entries deserve a closer look. The O(1) average insert for a heap comes from the fact that a random new element usually belongs near the bottom, so it rises about 1.6 levels on average no matter how large the heap is. That is why heaps feel faster than their worst-case bound suggests. The O(n) build is the surprising one, and it has a real proof: most nodes sit near the leaves, where sifting down costs almost nothing. I covered that argument in the essay on why heapify is O(n) and not O(n log n), and the array layout that makes it possible is described in heap as array.

Now the worked example with real numbers. Suppose you have a stream of 1,000,000 integers and you want the 10 largest.

  • Min-heap of size 10. Keep a heap holding the best 10 so far. For each incoming value, compare it to the root (the smallest of your ten). If it is not bigger, discard it: one comparison. If it is bigger, replace the root and sift down, about log2(10), roughly 3 levels. For random input, only about 10 * ln(1,000,000 / 10), roughly 115 elements ever displace the root, so the total is about 1,000,000 comparisons plus a few hundred swaps. Memory is 10 integers.
  • Balanced BST of everything. Insert all 1,000,000 values at about 20 comparisons each (log2 of a million is about 19.9), so roughly 20 million comparisons, then walk to the maximum. Memory is a million nodes. In C++, a std::set node carries three pointers plus colour and key, around 40 bytes, so about 40 MB against 40 bytes for the heap.
  • Balanced BST capped at 10. You could insert and delete the minimum to keep it at ten nodes. That works, at about 3 to 4 comparisons per element plus allocation churn, but you have paid for ordering machinery you never use.

For this question the heap is about 20 times less work than the naive tree and uses a millionth of the memory. Flip the question and the verdict flips. Say you need to answer 100,000 queries of the form "what is the smallest stored value that is at least x?" A BST answers each in about 20 steps, 2 million steps total. A heap has no way to do it short of scanning, which is up to 100 billion steps. Same two structures, opposite winners, because the question changed.

import heapq

def top_k(stream, k):
    heap = []
    for x in stream:
        if len(heap) < k:
            heapq.heappush(heap, x)
        elif x > heap[0]:
            heapq.heapreplace(heap, x)
    return sorted(heap, reverse=True)

The same idea powers Kth Largest Element, and the broader trade against sorting is in when to use a heap instead of sorting.

Why is a heap stored in an array while a BST uses nodes?

A heap fits in an array because its complete shape makes parent and child positions pure arithmetic: for a node at index i, the children are at 2i+1 and 2i+2 and the parent is at (i-1)/2. A BST has no fixed shape, so a node cannot know where its children live without storing pointers.

This has practical consequences beyond elegance. An array of a million 8-byte integers is 8 MB of contiguous memory. The CPU prefetcher loves it, and the top levels of the heap, which are touched on every operation, stay hot in cache. A pointer-based BST scatters nodes across the heap allocator, so each step down the tree is a potential cache miss costing on the order of 100 nanoseconds if it goes to main memory. Twenty levels of misses is 2 microseconds per lookup in the bad case. That is why a sorted array with binary search often beats a tree for read-heavy workloads, a theme I explored in why arrays beat linked lists in practice.

It also explains why you rarely write a BST by hand outside interviews. Production code reaches for a library tree (Java's TreeMap, C++'s std::map) that handles rebalancing for you. A heap, by contrast, is thirty lines you can write from memory, which is exactly why interviewers like it.

What goes wrong when a binary search tree is not balanced?

An unbalanced BST degrades into a linked list: its height becomes n instead of log n, and every operation that depends on height becomes O(n). The heap has no such failure mode, because its complete shape fixes the height at floor(log2 n) regardless of insertion order.

Here is the damage in numbers. Insert the keys 1 through 1,000,000 in order into a plain BST. Each key goes to the right of the previous one, so the i-th insert walks i nodes. The total is about n^2 / 2 = 500 billion node visits. At even a generous 5 nanoseconds per visit that is 2,500 seconds, over 40 minutes, to build something a heap builds in a few milliseconds. And sorted or nearly sorted input is not exotic; it is what timestamps, auto-incrementing IDs, and pre-sorted files look like.

Self-balancing trees fix this by rotating nodes during insert and delete so that height stays within a constant factor of log2 n. AVL trees keep height under about 1.44 log2 n; red-black trees allow up to 2 log2 n but rotate less often. The price is complexity and a constant-factor overhead, which is why the table above separates "balanced BST" from "plain BST". When someone says "BST operations are O(log n)", that is a contract that holds only with balancing, the same kind of hidden condition I argued for in complexity is a contract, not a fact.

Interviews have a related trap. A problem that gives you a BST does not give you balance, so an in-order traversal is O(n) and a search can be O(n). And validating one is a different task from using one: the common mistake is checking only a node against its immediate children, when the invariant spans the whole subtree. Validate BST is the cleanest way to feel that difference between a local rule (the heap's) and a global one (the BST's).

When should you pick a heap, and when a BST?

Pick a heap when you only ever need the best element and its removal; pick a balanced BST when you need lookup by key, ordered iteration, or neighbours such as floor, ceiling, predecessor, and successor. If your questions are about the extreme, order is a cost you do not need to pay.

A short decision list I actually use:

  • Top-k, running median halves, task scheduling, merging k sorted lists, Dijkstra's frontier. Heap. Every one of these repeatedly asks for the next smallest or largest item and nothing else.
  • Ordered set or map, range counts, "closest value to x", interval booking, sliding window with deletions by value. Balanced BST (or a sorted container).
  • Need both extremes at once. Two heaps, or one BST. A BST gives min and max in O(log n) and also supports deletion of arbitrary elements, which heaps do poorly. If you are tempted to bolt lazy deletion onto a heap, ask whether a tree would be simpler.
  • Static data, many lookups. Neither. Sort once and binary search, or use a hash map when you do not need order. See hash maps for that side of the trade.

One more framing helps when you are unsure. Count how many different questions you will ask of the data. One question (what is next?) means a heap. Several questions about position and order mean a tree. The more you ask, the more structure you must maintain, and structure has a price in memory, constant factors, and code.

Finally, a note on what not to conflate. Heap as a data structure is unrelated to the heap as a memory region used for dynamic allocation; they share a name by accident of history. And a BST is not a "sorted heap" or a "heap with search". They are different contracts over the same tree shape, and the shape itself is the less important half. If you want to see more of the tree side, the trees topic collects the standard problems.

Frequently asked questions

Is a heap a kind of binary search tree?

No. A heap orders parents against children only, while a BST orders whole subtrees against their root. A valid heap is almost never a valid BST: in the heap [1, 3, 9, 7, 5], node 3 has a right child 5 that is larger, which is fine, but its left child 7 is larger too, which breaks the BST rule.

Can a heap search for an element faster than O(n)?

Not in general. Because siblings and cousins have no order, the only pruning available is that you can skip a subtree whose root is already worse than your target. In the worst case you still visit every node, so searching by value is O(n). If you need fast lookup, add a hash map from value to index or use a BST.

Why do languages ship heaps as priority queues but trees as maps?

Because that matches the questions people ask. A priority queue exposes only push and pop-best, which a heap does with minimal overhead and memory. A map or ordered set exposes lookup, deletion by key, and ordered iteration, which needs the full ordering a balanced tree provides.

If you want to see the heap side under real pressure, work through Kth Largest Element next, once with sorting, once with a size-k heap, and count the comparisons yourself.