【问题标题】:Uniqueness of min heap? [duplicate]最小堆的唯一性? [复制]
【发布时间】:2016-03-20 03:41:49
【问题描述】:

我们可以从给定的唯一非堆列表中创建多个最小堆吗?

下面的L1L2(它们共享完全相同的元素,但顺序不同)都是这个原始非堆列表的合法最小堆:[12,12,3,12,12,12,12,9,6,6,10,4,20]

L1=[3,4,9,6,10,12,12,12,6,12,12,12,20] L2=[3,6,4,9,6,12,12,12,12,12,10,12,20]

这对我来说似乎很奇怪。是常识吗?我很想得到一些确认。

附录: 此 Python function 检查列表是否验证最小堆条件:heap[k] <= heap[2*k+1]heap[k] <= heap[2*k+2] 用于所有 k:

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

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

【问题讨论】:

    标签: python heap


    【解决方案1】:

    我可以指出max heap的这个相关问题吗?

    我认为简而言之,该问题的第二个答案涵盖了所有内容:堆约束(即子级大于父级)并没有完全指定堆,因此通常有多个可能的排列。对于最小堆,同样的约束也适用,所以同样,可能存在不止一种可能的排列,因此不能保证唯一性。

    【讨论】:

      猜你喜欢
      • 2011-12-02
      • 2018-06-02
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      相关资源
      最近更新 更多