The heap shape
After this: Read a heap array as a tree, using the rules for parent and child indexes.
On this page · 10 sections · 4 checks
In the last lesson you saw the goal: keep the smallest item at a known place, and keep push and pop cheap. A heap does this with two things you have met before, a tree and an array. This lesson shows how one row of values can be both.
A reminder about trees
A heap is a kind of binary tree. Here are the words you need.
- A is one item in a tree.
- Each node can have up to two children below it, a left child and a right child. The node directly above a node is its parent.
- The is the node at the top. It has no parent.
- A is a node with no children.
- A level is one row of the tree. The root is on level 0, its children are on level 1, and so on.
From a tree to an array
Here is a small tree.
To store it in an array, read the tree the way you read a page: the top row first, then each lower row from left to right. The binary trees tutorial calls this level order.
- The top level holds 1. Write it at index 0.
- The next level holds 3 and 8. Write them at indexes 1 and 2.
- The last level holds 5. Write it at index 3.
The array is [1, 3, 8, 5]. This table shows where each cell sits in the tree.
| Index | Value | Place in the tree |
|---|---|---|
| 0 | 1 | the root |
| 1 | 3 | left child of index 0 |
| 2 | 8 | right child of index 0 |
| 3 | 5 | left child of index 1 |
The computer stores only the array. The tree is a way of reading it.
No gaps: the complete tree
Reading a tree into an array works only if the tree has no gaps. Here is a different tree. Its node 5 is the right child of 3, and 3 has no left child.
Read this one in level order and you get 1, 3, 8, 5 again. That is the same array as before, so the array could not tell the two trees apart.
A heap avoids this problem by filling its tree in one fixed order. It fills each level from left to right, and it starts a new level only when the level above is full. A tree filled this way is called a . Only the bottom level can be part full, and its nodes sit to the left.
Our first tree is complete. The tree with the gap is not.
Finding children and parents
In a complete tree, every index has one fixed place. This drawing shows the first seven places. Each circle shows its index, not a value.
You can read each index's family from the drawing. The children of index 3 are on the next level down, which is not drawn.
| Index | Its parent is at | Its children are at |
|---|---|---|
| 0 | none: it is the root | 1 and 2 |
| 1 | 0 | 3 and 4 |
| 2 | 0 | 5 and 6 |
| 3 | 1 | 7 and 8 |
Now look for a pattern in the last column. Double the index, then add 1 and add 2.
- Index 1: double it to get 2. The children are 3 and 4.
- Index 2: double it to get 4. The children are 5 and 6.
- Index 3: double it to get 6. The children are 7 and 8.
The parent goes the other way. Subtract 1, halve the result, and round down.
- Index 3: 3 − 1 = 2, and half of 2 is 1. The parent is index 1.
- Index 4: 4 − 1 = 3, and half of 3 is 1.5, which rounds down to 1. The parent is index 1 again, because 3 and 4 share a parent.
Written as rules for any index i:
- the left child is at 2i + 1;
- the right child is at 2i + 2;
- the parent is at (i − 1) ÷ 2, rounded down.
In the binary trees tutorial, each node stored links to its two children. A stored link like this is called a . A heap needs no pointers, because a small calculation finds every child and every parent. This is why a heap can live in a plain array.
The heap rule
The shape alone does not put the smallest value at the top. So a heap has a second rule: every parent is less than or equal to its children. A complete tree that keeps this rule is called a .
Here is the check for [1, 3, 8, 5], one index at a time.
- Index 1 holds 3. Its parent, index 0, holds 1. 1 ≤ 3, so this is fine.
- Index 2 holds 8. Its parent, index 0, holds 1. 1 ≤ 8, so this is fine.
- Index 3 holds 5. Its parent, index 1, holds 3. 3 ≤ 5, so this is fine.
Every parent passes, so [1, 3, 8, 5] is a min-heap. Now try [3, 1, 8, 5]. Index 1 holds 1 and its parent holds 3. 3 is larger than 1, so this array breaks the rule.
If you follow any path downward, the values never get smaller. So nothing in the heap can be smaller than the root, and the root is the smallest value of all.
Because the smallest is always at index 0, a program can read it in one step without changing anything. This is called , and it is O(1).
What the rule does not promise
The rule compares a parent with its own children, and nothing else. So a heap has much less order than a sorted list.
- Two children of the same parent can be in either order.
[1, 5, 3, 8]is a valid heap, and so is[1, 3, 8, 5]. - The array is not always sorted.
[1, 3, 8, 5]is not. - The last value is not always the largest.
[1, 3, 8, 5]ends with 5, but 8 is larger.
This small amount of order is what keeps a heap cheap to change.
The code
Here are the three rules and the heap rule as code.
def parent(i): return (i - 1) // 2
def left(i): return 2 * i + 1
def right(i): return 2 * i + 2
def is_min_heap(items): return all(items[parent(i)] <= items[i] for i in range(1, len(items)))
heap = [1, 3, 8, 5]print(left(0), right(0), left(1)) # children of index 0: 1 and 2; left child of index 1: 3print(parent(3), parent(2)) # 5 at index 3 sits under index 1; 8 at index 2 under index 0print(is_min_heap(heap), is_min_heap([1, 5, 3, 8]), is_min_heap([3, 1, 8, 5]))1 2 3 1 0 True True False
public class HeapIndexes { static int parent(int i) { return (i - 1) / 2; } static int left(int i) { return 2 * i + 1; } static int right(int i) { return 2 * i + 2; }
static boolean isMinHeap(int[] items) { for (int i = 1; i < items.length; i++) { if (items[parent(i)] > items[i]) return false; } return true; }
public static void main(String[] args) { int[] heap = {1, 3, 8, 5}; System.out.println(left(0) + " " + right(0) + " " + left(1)); // children of index 0: 1 and 2; left child of index 1: 3 System.out.println(parent(3) + " " + parent(2)); // 5 at index 3 sits under index 1; 8 at index 2 under index 0 System.out.println(isMinHeap(heap) + " " + isMinHeap(new int[] {1, 5, 3, 8}) + " " + isMinHeap(new int[] {3, 1, 8, 5})); }}1 2 3 1 0 true true false
Here is how to read it.
parent,leftandrightare the three rules. // divides and rounds down.Dividing two whole numbers with / drops the remainder, which rounds down here.- is_min_heapisMinHeap goes through every index from 1 to the end and compares it with its parent. It starts at 1 because the root has no parent.
- The first printed line shows that the children of index 0 are at 1 and 2, and that the left child of index 1 is at 3.
- The second printed line shows that the parent of index 3 is 1, and the parent of index 2 is 0.
- The third printed line tests three arrays. The first two are valid heaps, and
[3, 1, 8, 5]is not.
Watch it happen
The heap holds [1, 3, 8, 5]. Peek, then push two values that are larger than their parents, and watch where the array puts them.
- PeekPeek. The smallest value is at index 0, the root, so no search is needed.
- Push 9
- Push 10
- 01
- 13
- 28
- 35
Push a few values and watch them sift up.
Check yourself
In a heap array, which indexes hold the two children of index 2?
Which index holds the parent of index 9?
Which statement does the min-heap rule guarantee?
Which of these arrays is a valid min-heap?
Connect
The next lesson uses these rules to add a value to a heap.
- Read a complete binary tree into an array, level by level, with no pointers.
- Find the children of index i at 2i + 1 and 2i + 2, and its parent at (i − 1) ÷ 2, rounded down.
- State the heap rule: every parent is ≤ its children, so the root is the smallest value.
- Say why a heap is not a binary search tree: its values have less order, so finding one value means looking through the array.