Heaps
Heaps
1
Binary SearchTrees
When discussing binary search trees we looked at
examples like
The value stored at each node of the tree is greater than or equal to
the values stored in its left subtree, and greater than or equal to
the values stored in its right subtree.
Note that the value at a node is now greater than or equal to the
values in both subtrees
Note: A heap data structure should not be confused with the heap which is a
common name for dynamically allocated memory.
Binary Heaps Trees
Properties:
A simple local test for whether the heap property holds is
that the value stored at every node should be no greater
than the value stored at its parent
It follows that every path from the root to a leaf forms a
decreasing sequence.
The maximum number of children each node can have
depends on the type of heap, but in many types it is at
most two
A complete binary tree which also satisfies the
ordering heap property is called a binary heap.
Complete Binary Tree
Recall that a binary tree of height h is said to be
complete if it is full down to level h – 1, and level h is
filled from left to right.
Examples:
6
Arithmetic Tree Traversal
10
Sorting:
Step 1: Build a heap/Insert
Step 2: remove( )
Priority queue
To implement priority queues
Priority queue = a queue where all elements have a “priority”
associated with them
Remove in a priority queue removes the element with the
50 45
15 40 35 20
5 10 25 30 47
Solution
55
50 47
15 40 45 20
5 10 25 30 35
Removal, deletion
The procedure for deleting the root from the heap (effectively
extracting the maximum element in a max-heap or the
minimum element in a min-heap) and restoring the properties
is called down-heap (also known as bubble-down , heapify-down
and extract-min/max).
Replace the root of the heap with the last element on the last
level.
Compare the new root with its children; if they are in the
correct order, stop.
If not, swap the element with one of its children and return to
the previous step. (Swap with its smaller child in a min-heap
and its larger child in a max-heap.)
Removal Algorithm
Remove() will remove 40 from the heap. Which
element will be the root then?
60
55 45
15 50 35 20
5 10 40 30 25
23
Solution
55
50 45
15 40 35 20
5 10 25 30
Examples insertion(min)
Putting an element 2 into a priority Queue
Insert 12
Solution
Remove Min
Solution