algoritmauzmanı
Sign in
TREN
7Heaps and Balanced Trees
Lesson 7.0

What is a heap?

In the priority queue lessons you saw that every structure was slow either at insertion or at removal. A does both in . It manages this with two simple rules: the tree always stays , and every node is smaller than its children. This lesson covers what a heap is, what it is not and where it is used.

What you will learn
  • The two rules a tree must meet to be a heap
  • The difference between a and a
  • How a heap differs from a binary search tree, and why it is fast
6 min

1Two rules

A heap is a . For a binary tree to count as a heap, two rules must hold together:

  1. Shape rule: the tree is . Every level except the last is full, and the last level fills from left to right.
  2. Order rule: every node is smaller than or equal to its children. This is called the .

The second rule holds between every parent and child, so it chains: the root is smaller than its children, they are smaller than theirs, and so on. As a result the smallest value is always at the root. The tree below is a heap.

10201540503025
A min-heap. Every node is smaller than its children; the smallest value, 10, is at the root (green). There is no order between 20 and 15: siblings are free.

2Min-heap and max-heap

The order rule can point either way. A heap where every node is smaller than or equal to its children is a ; one where every node is larger than or equal to its children is a . A min-heap has the smallest value at its root, a max-heap the largest. Both are written with the same code; only the direction of the comparison changes.

50403010201525
The same seven values as a max-heap. The largest value, 50, is at the root.

The heap lessons on this site use a min-heap; as in the priority queue lessons, the smaller value comes out first. We will need a max-heap in the heap sort lesson. In an exam, check which one is being asked for.

3Two trees that are not heaps

The order rule is checked only between a parent and its children. In the tree below 12 is smaller than its parent 20. Even though the root is still the smallest value, the tree is not a heap.

10201540123025
The heap property is broken: 20's child 12 is smaller than it (orange link).

The shape rule matters just as much. In the tree below the order rule holds everywhere, but the last level has a gap after 40 and the nodes on the right come after that gap. The tree is not complete, so it is not a heap.

102015403025
Not complete: 20 has no right child while 15 has children. This tree cannot sit in an array without gaps.

4Why is a heap fast?

In a complete tree each level holds twice as many nodes as the one above: 1, 2, 4, 8. So a complete tree with n nodes has a height equal to the whole part of log₂ n. With 1000 nodes the height is 9; with a million it is 19. Every heap operation moves along a single path, from the root to a leaf or from a leaf to the root, so it takes at most as many steps as the height.

OperationTimeHow
Look at the minimum (peek)O(1)Read the root
InsertO(log n)Put it at the end, move it up: sift up
Remove the minimumO(log n)Move the last one to the root, move it down: sift down
Build a heap from n valuesO(n)Heapify
Search for a valueO(n)The order rule does not help a search

A complete tree brings one more advantage: it fits in an array with no gaps. The index formulas from binary tree in an array work for a heap too, and no pointers are needed. That is why a heap is almost always coded with an array.

5Heap versus binary search tree

Both are binary trees and both have an order rule, but the rules differ. In a binary search tree the left subtree is smaller and the right subtree is larger; that speeds up searching for a value, and an inorder traversal returns the values sorted. In a heap there is an order only between parent and child, not between left and right.

HeapBinary search tree
Order ruleParent ≤ childrenLeft < node < right
ShapeAlways completeDepends on insertion order
Smallest valueAt the root, O(1)The leftmost node
Search for a valueO(n)O(log n) if balanced
Inorder traversalNot sortedSorted
Usually coded withAn arrayLinked nodes

6Where are heaps used?

  • Priority queues: as you saw in the priority queue comparison, a heap makes both insertion and removal fast. Java's java.util.PriorityQueue and Python's heapq are binary heaps.
  • Sorting: heap sort sorts an array in O(n log n) with no extra memory.
  • The k largest items: to keep the 10 largest values of a huge stream of data, a min-heap of 10 elements is enough.
  • Graph algorithms: shortest paths (Dijkstra) and minimum spanning trees (Prim) take the next closest vertex from a heap.
  • Operating systems and timers: a heap finds the job whose time runs out first.

The word "heap" also appears in memory management: the region where C's malloc hands out memory is called the heap too. There is no link between the two; the same word is used for two different things.

7What this part covers

8Try it

Is the tree holding 5, 9, 7, 12, 10, 6 in level order a min-heap?

Show the answer

The answer is C. 6 sits at position 5; its parent is at (5-1)/2 = 2, which holds 7, and since 7 > 6 the rule is broken. 10 is at position 4; its parent at (4-1)/2 = 1 holds 9, and 9 < 10, so there is no problem there.

What is the height of a heap with 10 nodes (height counted in edges)?

Show the answer

The answer is A. A complete tree fills its levels as 1, 2, 4: the first three levels hold 7 nodes, and the remaining 3 go into the fourth level. Four levels mean 3 edges between the root and the deepest leaf.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.