Priority Queues
Class Materialβ
- Slides can be found here.
Why total number of leaves = β
Number of leaves Total number of nodes in all layers above
Min/Max Heapβ
Heap Shapeβ
Holes always appear in the last layer, and they are always to the right of the last node in the last layer.
Order of Operationsβ
When modifying a heap, always (1) Update the structure and (2) Fix the heap property, in that specific order. That is, when deleting a node, first replace the node with the last node in the heap, then fix the heap property (trickle down). When inserting a node, first insert the node at the end of the heap, then fix the heap property (bubble up).
Operation Complexitiesβ
- Create a heap (Heapify): - This is the reason we use Heaps instead of Binary Trees in the first place. Enough structure to get things done, and not enough structure to bog us down.
- Insert: - Bubble up touches only it's own path to the root, which is the height of the tree.
- Delete: - Trickle down touches only it's own path to the last layer, which is the height of the tree.
- Find Min/Max: - The root of the heap.
Traversing a Heapβ
Watch out for 0-based or 1-based indexing errors!
- Get to parent:
- Get the left child:
- Get the right child:
- Get to a position, n. (using bitstring):
- Construct bitstring using binary representation of n.
- Ignore the leftmost bit.
- If the bit is 0, go left.
- If the bit is 1, go right.
- Start at the root, and follow the bitstring.