3

我想编写一个函数来告诉我给定列表是否是最小堆。

到目前为止我所写的:

def is_min_heap(L):
    return _is_min_heap(L, 0)

def _is_min_heap(L, i):
    if 
         #base case
    else:
        return (L[i] < L[2*i+1] and _is_min_heap(L, 2*i+1)) and (L[i] < L[2*i+2] and _is_min_heap(L, 2*1+2))

我不确定基本情况应该是什么,我的递归调用是否正确?

另外,您如何控制索引最终不会超出范围?

4

1 回答 1

2

对于给定的,您有三种不同的情况i:您有两个孩子,在这种情况下,您需要检查两个孩子的堆属性并递归检查两个子树;或者你只有一个左孩子,在这种情况下你只需要检查那个;或者你没有孩子,即i是一片叶子,它本身总是一个有效的堆。

您可以通过检查子项的索引是否仍在列表范围内来检查子项的存在。

def _is_min_heap(L, i):
    l, r = 2 * i + 1, 2 * i + 2

    if r < len(L): # has left and right children
        if L[l] < L[i] or L[r] < L[i]: # heap property is violated
            return False

        # check both children trees
        return _is_min_heap(L, l) and _is_min_heap(L, r)
    elif l < len(L): # only has left children
        if L[l] < L[i]: # heap property is violated
            return False

        # check left children tree
        return _is_min_heap(L, l)
    else: # has no children
        return True
于 2013-04-07T17:13:22.330 回答