How can I write a function that can accept a binary tree as a parameter and returns True if it is a min heap and False if not.
from heapq import heapify
def binary_heap(tree):
while len(tree) > 1:
if heapify(tree):
return True
else:
return False
Since a min heap has to satisfy, per
heapq's documentation:You can iterate through all child nodes to validate that they are greater than or equal to their parent nodes (note that
i - 1 >> 1is a shorthand for(i - 1) // 2wheni > 0):so that:
outputs something like:
Demo: https://ideone.com/1uhd6c