

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Priority Queues
incomplete
2: Priority Queue Code
incomplete
3: Heaps
incomplete
4: Why Use Heaps?
incomplete
5: Pop
incomplete
6: Priority Queue With a Heap
incomplete
This lesson's interactive features are locked, please to keep using them
Click to play video
Before we can improve our priority queue, we need to learn about heaps. A heap data structure is optimized for retrieving the largest or smallest element in a collection.
In the case of a max heap, it's a balanced tree where the value of each node is always greater than or equal to the value of its children. A min heap is the opposite, where the value of each node is less than or equal to the value of its children. This property is called the heap property.
That means the root node is either the largest or smallest element in the tree, so finding the min or max (depending on the type of heap) is a blazingly fast operation.
A list can be used to represent a heap. This may seem tricky, but by doing some math with the indexes in the list, we can keep track of the tree structure.
The min heap above can be represented like so:
[8, 10, 9, 21, 31, 27, 12, 58, 99, 42, 33, 39]
Our min heap will need several methods. For now, complete the push and bubble_up methods.
self.elements is a list of tuples where the first index is the priority (a number) and the second index is the value of the element, in our case a street name.
The formula for finding the index of the parent node:
parent_index = (index - 1) // 2