A Min-Heap is a Data Structure with the following properties.
- It is a complete Complete Binary Tree.
- The value of the root node must be the smallest among all its descendant nodes and the same thing must be done for its left and right sub-tree also.
The elements of a heap can be mapped into an array using the following rules:
If a node is stored at index k:
- Left child is stored at index 2k + 1 (for 0-based indexing) or 2k (for 1-based indexing).
- Right child is stored at index 2k + 2 (for 0-based indexing) or 2k + 1 (for 1-based indexing).
Example of Min Heap
Tree Representation:
5 13
/ \ / \
10 15 16 31
/ / \ / \
30 41 51 100 41
Array Representation:
For the first tree:
[5, 10, 15, 30]
For the second tree:
[13, 16, 31, 41, 51, 100, 41]
Min Heap Representation as an Array
Since a Min Heap is a Complete Binary Tree, it is commonly represented using an array. In an array representation: The root element is stored at Arr[0]. For any i-th node (at Arr[i]):
- Parent Node -> Arr[(i - 1) / 2]
- Left Child -> Arr[(2 * i) + 1]
- Right Child -> Arr[(2 * i) + 2]
Operations on Min Heap
- getMin(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).
- extractMin(): Removes the minimum element from MinHeap. Time Complexity of this Operation is O(Log n) as this operation needs to maintain the heap property (by calling heapify()) after removing root.
- insert(): Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If new key is larger than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.
Python Implementation
Please refer Min-Heap for details.
Output
Min Heap: [4, 5, 11, 10, 7, 13]
Heap after deleting 7: [4, 5, 11, 10, 13]
Searching for 10 in heap: Found
Minimum element in heap: 4
Using Python’s heapq Library
Python’s heapq module implements a Min Heap by default.
OutputHead value of heap : 10
The heap elements :
10 30 20 400
The heap elements :
20 30 400
Using queue.PriorityQueue
Please refer queue.PriorityQueue for details.