是什么是最小堆函数?

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))

我不确定基本情况应该是什么,我的递归调用是否正确? 此外,您如何控制索引最终不超出范围?
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接