创建堆(python)
创建最大(小)堆
二叉堆本质上是一种完全二叉树,存储方式并不是链式存储,而是顺序存储
-
堆操作:插入(叶子节点上调),删除(堆顶元素下沉)
-
堆创建:非叶子节点下沉(从最后一个非叶子节点开始)
-
最小堆:
最小堆任何一个父节点的值,都小于等于它左右孩子节点的值
创建过程:如果非叶子节点值大于其子节点,将其下沉
-
最大堆:
最大堆任何一个父节点的值,都大于等于它左右孩子节点的值。
创建过程:如果非叶子节点值小于其子节点,将其下沉
-
#最小堆
def upadjust(nums):
childindex = len(nums)-1
parentindex = (childindex-1)//2
temp = nums[childindex] #插入的叶子节点值
while childindex>0 and temp<nums[parentindex]:#子节点小于父节点,上调子节点
nums[childindex] = nums[parentindex]
childindex = parentindex
parentindex = (parentindex-1)//2
nums[childindex] = temp
def downadjust(nums,parentindex):
temp = nums[parentindex]
childindex = 2*parentindex + 1
while childindex < len(nums):
#右孩子值小于左孩子,父节点和小的交换
if childindex +1 <len(nums) and nums[childindex+1] < nums[childindex]:
childindex += 1
if temp < nums[childindex]: #父节点小于子节点,不用调整
break
nums[parentindex] = nums[childindex]
parentindex = childindex
childindex = childindex*2+1
nums[parentindex] = temp
def buildMinHeap(nums):
for i in range((len(nums)-1)//2,-1,-1):
downadjust(nums,i)
>>> nums = [5,8,6,3,9,2,1,7,0]
>>> buildMinHeap(nums)
>>> nums
[0, 3, 1, 5, 9, 2, 6, 7, 8]
#最大堆
#非叶子节点小值下沉
def downadjust(nums,parentindex):
temp = nums[parentindex]
childindex = 2*parentindex + 1
while childindex < len(nums):
if childindex +1 <len(nums) and nums[childindex+1] > nums[childindex]:#右孩子值大于左孩子,父节点和大的交换
childindex += 1
if temp > nums[childindex]: #父节点大于子节点,不用调整
break
nums[parentindex] = nums[childindex]
parentindex = childindex
childindex = childindex*2+1
nums[parentindex] = temp
def buildMaxHeap(nums):
for i in range((len(nums)-1)//2,-1,-1):
downadjust(nums,i)
>>> nums = [5,8,6,3,9,2,1,7,0]
>>> buildMaxHeap(nums)
>>> nums
[9, 8, 6, 7, 5, 2, 1, 3, 0]
python自带堆模块
>>> import heapq
#默认最小堆
>>> nums = [5,8,6,3,9,2,1,7,0]
>>> heapq.heapify(nums)
>>> nums
[0, 3, 1, 5, 9, 2, 6, 7, 8]