Skip to content Skip to sidebar Skip to footer

Is Min Heap Function

I want to write a function that tells me whether a given list is a min heap. What I have written so far: def is_min_heap(L): return _is_min_heap(L, 0) def _is_min_heap(L, i):

Solution 1:

You have three different cases for a given i: Either you have two children, in which case you need to check the heap property for both children and also recursively check both subtrees; or you have just a left children, in which case you just have to check that one; or you have no children, i.e. i is a leaf, which is always a valid heap by itself.

You can check the existence of a children by checking if its index is still in range with the list.

def_is_min_heap(L, i):
    l, r = 2 * i + 1, 2 * i + 2if r < len(L): # has left and right childrenif L[l] < L[i] or L[r] < L[i]: # heap property is violatedreturnFalse# check both children treesreturn _is_min_heap(L, l) and _is_min_heap(L, r)
    elif l < len(L): # only has left childrenif L[l] < L[i]: # heap property is violatedreturnFalse# check left children treereturn _is_min_heap(L, l)
    else: # has no childrenreturnTrue

Post a Comment for "Is Min Heap Function"