【发布时间】:2016-03-20 03:41:49
【问题描述】:
我们可以从给定的唯一非堆列表中创建多个最小堆吗?
下面的L1 和L2(它们共享完全相同的元素,但顺序不同)都是这个原始非堆列表的合法最小堆:[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
【问题讨论】: