- A min heap is a binary tree in which the parent nodes hold smaller values than that of the children.
- As new elements get added into the heap, the “heap” property stated above is maintained.
- The heapq module in Python provides a set of functions to create and manipulate min heaps.
- The heappush() method pushes an element into an existing heap in such a way that the heap property is maintained.
The Python example constructs a min heap through heapify() function and subsequently calls heappush() twice to add two elements into the heap, while maintaining the heap property.
# Example Python program that pushes elements into a heap
# while maintaining the heap property
# Data as a Python list
heapData = [10, 50, 60, 20, 70]
# Make the Python list into a heap
# Print the heap
# Push new elements into the heap
[10, 20, 60, 50, 70]
[10, 20, 40, 50, 70, 60]
[10, 20, 30, 50, 70, 60, 40]