pythonbinary-treebinary-search-treebreadth-first-searchmin-heap

Is there a Python method to check whether a binary tree is a min heap?


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

Solution

  • Since a min heap has to satisfy, per heapq's documentation:

    heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2]
    

    You can iterate through all child nodes to validate that they are greater than or equal to their parent nodes (note that i - 1 >> 1 is a shorthand for (i - 1) // 2 when i > 0):

    def is_minheap(lst):
        return all(lst[i] >= lst[i - 1 >> 1] for i in range(1, len(lst)))
    

    so that:

    from heapq import heapify
    from random import sample
    
    lst = sample(range(10), 10)
    print(is_minheap(lst), lst)
    heapify(lst)
    print(is_minheap(lst), lst)
    

    outputs something like:

    False [1, 2, 6, 8, 0, 5, 3, 9, 7, 4]
    True [0, 1, 3, 7, 2, 5, 6, 9, 8, 4]
    

    Demo: https://ideone.com/1uhd6c