Bitpath

Lesson 1 · Unit 03

A tree in an array

The heap rule, complete trees and index maths

11 exercisesabout 3 min

What you practise

  • Complete trees, index maths, the heap property

Try a question from this lesson

Pick one

You keep n waiting jobs in a sorted array so the most urgent is always first. A new job arrives. What does it cost to put it in its sorted place?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The heap rule

A min-heap is a binary tree with one rule: every parent is less than or equal to its children.

So the smallest value is always at the root. Siblings are in no particular order: 3 and 2 could swap sides and the rule would still hold.

The tree is stored level by level in a plain array.

#        1
#      /   \
#     3     2
#    / \   /
#   7   4 5
heap = [1, 3, 2, 7, 4, 5]
print(heap[0])
//        1
//      /   \
//     3     2
//    / \   /
//   7   4 5
const heap = [1, 3, 2, 7, 4, 5];
console.log(heap[0]);
//        1
//      /   \
//     3     2
//    / \   /
//   7   4 5
const heap: number[] = [1, 3, 2, 7, 4, 5];
console.log(heap[0]);

Python noteA heap in Python is an ordinary list. The order of the items is what makes it a heap.

TypeScript notenumber[] is all the type a heap needs: an array of numbers. There is no node class and there are no child links.

Concept

Children and parents by arithmetic

A heap is always a complete tree: every level is full, and the last one fills from the left. With no gaps, the level-by-level array needs no links at all.

For the item at index i: its children are at 2i + 1 and 2i + 2, and its parent is at (i - 1) divided by 2, rounded down.

heap = [1, 3, 2, 7, 4, 5]
i = 1
print(heap[2 * i + 1])
print(heap[2 * i + 2])
parent = (i - 1) // 2
print(heap[parent])
const heap = [1, 3, 2, 7, 4, 5];
const i = 1;
console.log(heap[2 * i + 1]);
console.log(heap[2 * i + 2]);
const parent = Math.floor((i - 1) / 2);
console.log(heap[parent]);
const heap = [1, 3, 2, 7, 4, 5];
const i = 1;
console.log(heap[2 * i + 1]);
console.log(heap[2 * i + 2]);
const parent = Math.floor((i - 1) / 2);
console.log(heap[parent]);

Python note// is integer division: it rounds down, so 3 // 2 is 1.

JavaScript note/ always gives a fraction in JavaScript (3 / 2 is 1.5), so Math.floor rounds it down to a usable index.

TypeScript note/ gives a fraction, so Math.floor rounds down. An index like 1.5 would type-check as a number and then read undefined.

8 more exercises in the app

  • 1× true or false
  • 3× type the answer
  • 1× fill the blanks
  • 2× multiple choice
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy