繁体   English   中英

使用列表无法满足 maxheap 属性

[英]Having trouble satisfying the maxheap property using a list

我正在创建一个 MaxHeap 类,我必须使用列表来完成它。 我无法以正确的顺序将元素插入堆以满足 maxheap 要求。 我不允许向构造函数添加任何内容。 我该怎么办?

class MaxHeap:  

    def __init__(self):
        self.Heap=[]

    def parent(self, pos): 
        return pos//2


    def leftChild(self, pos): 
        return 2 * pos 


    def rightChild(self, pos): 
        return (2 * pos) + 1

    def insert(self, element):
        self.Heap.append(element)
        child = len(self.Heap) - 1

        while child > 0:
            parent = self.parent(child)
            if self.Heap[parent] >= self.Heap[child]:
                return

            self.Heap[child], self.Heap[parent] = self.Heap[parent], self.Heap[child]
            child = parent

我的代码做什么(左)与预期(右)(以 | 分隔)

x = MaxHeap()

x.插入(10)

  • [10] | [10]

x.插入(5)

  • [10,5] | [10,5]

x.插入(14)

  • [14,10,5] | [14,5,10] -> 首先事情开始出错

x.插入(9)

  • [14,10,5,9] | [14,9,10,5]我的代码又错了,其余的也是

x.插入(2)

  • [14,10,5,9,2] | [14,9,10,5,2]

x.插入(11)

  • [14,11,10,9,2,5] | [14,9,11,5,2,10]

x.插入(6)

  • [14,11,10,9,2,5,6] | [14,9,11,5,2,10,6]

插入14的时候,最初是10的右孩子,然后你交换14和10,堆的层级遍历就是数组表示,14是父级,5是左孩子,10是右孩子等等。

当我最初添加 14 时,它从 [10,5] 变为 [10,5,14]

使用 [10,5,14],我将 14 与其父项进行比较,即 10。这不满足最大堆属性,因此我必须将 10 与 14 进行切换,使其变为 [14,5,10]

我该怎么做他的?

Python 列表的索引从 0 开始,但您使用的父/子公式用于以 1 为根的堆。

对于根为 0 的堆:

leftChild(x) = x*2+1
rightChild(x) = x*2+2
parent(x) = (x-1)//2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM