binary heap 是一个完全二叉树,存储在数组中,并维持 堆属性:在 min-heap 中,每个父节点都小于等于(≤)其子节点,因此 最小值始终位于根节点。这使其成为实现 priority queue 的标准方案。
数组布局
text
1 index: 0 1 2 3 4
/ \ array: [1, 3, 5, 8, 4]
3 5 parent(i) = (i-1)//2
/ \ left(i) = 2i+1
8 4 right(i) = 2i+2
操作
python
heapq
h = []
heapq.heappush(h, )
heapq.heappush(h, )
heapq.heappush(h, )
smallest = h[]
heapq.heappop(h)
