在给定键处拆分堆

时间:2019-02-18 19:13:42

标签: python heap

给出一个列表:[10、4、9、3、2、5、8、1、0]

具有以下堆结构:

        8
    9
        5
10
        2
    4
            0
        3
            1

在python中获得[4,3,2,1,0]的基本算法是什么,这基本上是10的左孩子。

父母是(index + 1)// 2

左边的孩子是2i + 1,右边的孩子是2i + 2

L = [10, 4, 9, 3, 2, 5, 8, 1, 0]
index = 1
newheap = []
newheap.append(L[index])
leftc = 2 * index + 1
rightc = 2 * index + 2
while(leftc < len(L)):
    newheap.append(L[leftc])
    if(rightc < len(L)):
        newheap.append(L[rightc])
    leftc = 2 * leftc + 1
    rightc = 2 * rightc + 2

print(newheap)

输出

[4,3,2,1]

但是我需要[4,3,2,1,0],所以不是我想要的。我从指向4的1开始索引。

递归会更好吗?不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以尝试类似的方法:

L = [10, 4, 9, 3, 2, 5, 8, 1, 0]
index = 0
offset = 1
newheap = []
while index < len(L):
    index += offset
    for i in range(offset):
        if index+i == len(L):
            break
        newheap += [L[index+i]]
    offset = 2 * offset
print(newheap)