插入最大堆时遇到问题
Having trouble inserting in a max heap
我正在创建一个 MaxHeap class,我必须使用一个列表来完成它。我无法将元素插入堆中。我不允许向构造函数添加任何内容。我该怎么办?
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[self.__len__] = x
current = self.__len__
while self.Heap[current] > self.Heap[self.parent(current)]:
self.Heap[current], self.Heap[self.parent(current)] = self.Heap[self.parent(current)], self.Heap[current]
current = self.parent(current)
试试这个(更新):
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
我正在创建一个 MaxHeap class,我必须使用一个列表来完成它。我无法将元素插入堆中。我不允许向构造函数添加任何内容。我该怎么办?
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[self.__len__] = x
current = self.__len__
while self.Heap[current] > self.Heap[self.parent(current)]:
self.Heap[current], self.Heap[self.parent(current)] = self.Heap[self.parent(current)], self.Heap[current]
current = self.parent(current)
试试这个(更新):
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