【问题标题】:Is Min Heap Function是最小堆函数
【发布时间】:2013-03-29 16:03:41
【问题描述】:

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

到目前为止我所写的:

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

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

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

【问题讨论】:

    标签: python heap min-heap


    【解决方案1】:

    对于给定的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
    

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 2012-12-31
      相关资源
      最近更新 更多