import heapq
listForTree = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
heapq.heapify(listForTree) # for a min heap
heapq._heapify_max(listForTree) # for a maxheap!!
import heapq
Since the built in heapq library is a minheap, multiply your values by -1
and it will function as a max heap. Just remeber that all your numbers
have been inverted.
Python's heap is a min heap.
# Python3 program to demonstrate working of heapq
from heapq import heappop, heappush, heapify
# Creating empty heap
heap = []
heapify(heap)
# Adding items to the heap using heappush
# function by multiplying them with -1
heappush(heap, -1 * 10)
heappush(heap, -1 * 30)
heappush(heap, -1 * 20)
heappush(heap, -1 * 400)
# printing the value of maximum element
print("Head value of heap : "+str(-1 * heap[0]))
# printing the elements of the heap
print("The heap elements : ")
for i in heap:
print(-1 * i, end = ' ')
print("
")
element = heappop(heap)
# printing the elements of the heap
print("The heap elements : ")
for i in heap:
print(-1 * i, end = ' ')
Step 1 − Create a new node at the end of heap.
Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.