如何在Python中实现堆遍历

时间:2016-07-19 19:19:03

标签: python heap binary-tree tree-traversal

我刚刚在python中创建了一个堆类,我仍在使用Tree遍历。当我调用None is not in the list时,我收到错误left。在我的三个遍历函数中,它们都需要rightclass myHeap: heapArray = [] def __init_(self): self.heapArray = [] def __str__(self): string = " ".join(str(x) for x in self.heapArray) return string def makenull(self): self.heapArray = [] def insert(self, x): self.heapArray.append(x) self.upheap(self.heapArray.index(x)) def parent(self, i): p = (i - 1) / 2 p = int(p) if(p >= 0): return self.heapArray[p] else: return None def left(self, i): l = (i + 1) * 2 - 1 l = int(l) if(l < len(self.heapArray)): return self.heapArray[l] else: return def right(self, i): r = (i + 1) * 2 r = int(r) if(r < len(self.heapArray)): return self.heapArray[r] else: return None def swap(self, a, b): temp = self.heapArray[a] self.heapArray[a] = self.heapArray[b] self.heapArray[b] = temp def upheap(self, i): if(self.parent(i) and self.heapArray[i] < self.parent(i)): p = (i - 1) / 2 p = int(p) self.swap(i, p) i = p self.upheap(i) else: return def downheap(self, i): if(self.left(i) and self.right(i)): if(self.left(i) <= self.right(i)): n = self.heapArray.index(self.left(i)) self.swap(i, n) self.downheap(n) else: n = self.heapArray.index(self.right(i)) self.swap(i, n) self.downheap(n) elif(self.left(i)): n = self.heapArray.index(self.left(i)) self.swap(i, n) self.downheap(n) elif(self.right(i)): n = self.heapArray.index(self.right()) self.swap(i,n) self.downheap(n) else: return def inorder(self, i): if(self.heapArray[i] != None): self.inorder(self.heapArray.index(self.left(i))) print(self.heapArray[i], end=" ") self.inorder(self.heapArray.index(self.right(i))) def preorder(self, i): if(self.heapArray[i] != None): print(self.heapArray[i], end=" ") self.preorder(self.heapArray.index(self.left(i))) self.preorder(self.heapArray.index(self.right(i))) def postorder(self, i): if(self.heapArray[i]!= None): self.postorder(self.heapArray.index(self.left(i))) self.postorder(self.heapArray.index(self.right(i))) print(self.heapArray[i], end=" ") def min(self): return self.heapArray[0] def deletemin(self): self.swap(0, len(self.heapArray) - 1) self.heapArray.pop self.downheap(0) def main(): heap = myHeap() heap.insert(0) heap.insert(15) heap.insert(7) heap.insert(8) heap.insert(1) heap.insert(2) heap.insert(22) print(heap) print(heap.heapArray[0]) heap.inorder(0) heap.preorder(0) heap.postorder(0) if __name__ == "__main__": main() 函数。我认为问题出在这两个函数中,但我不知道如何修复它。

IN

2 个答案:

答案 0 :(得分:0)

当你将树跟随其左边的孩子,并且没有左孩子时,那么你应该完成那条路径。你保证最终会得到无左子,这应该是你结束递归的基本情况。

相反,您查找左子项的值(使用其索引),然后反向计算您已从该值中获得的索引(希望没有重复项)。由于最终会有无左子,当你尝试反向计算无索引时,你会发现“self.heapArray”中没有None并且得到了确切的错误“None not not in list”

答案 1 :(得分:0)

想象一下当您在叶节点上调用inorder时会发生什么。它进入if语句的主体并尝试获取叶子节点的左右子节点 - 但是没有子节点 - 所以当self.left(i)求值为None并且被馈送到{{1 }} 方法。您需要修改结束递归的方式,以检查节点是否有左右子节点。