首先介绍树的完整性定义。一棵树满足以下条件时,则称树是完整的:
* 所有的非叶节点都是满的。
* 若底层没有满,则底层的所有节点尽可能靠左。
以二叉最小堆为例讲解以下内容。一棵二叉树满足以下条件时称为二叉最小堆:
* 树是完整的。
* 所有的子节点不小于父节点。
对于最小堆结构,remove_smallest
与add
是两个最常见的操作。
remove_smallest
拿掉堆最顶部的最小值,为了保持树的完整性,下方的元素需要不断上移,直至二叉最小堆条件重新被满足。
add
添加节点。实际上,与二叉树不同,二叉最小堆难以从根节点开始查找。因此,添加节点时,直接将新节点添加到底层的最左方以保持树的完整性。然后将该新节点上移直至二叉最小堆条件重新被满足。
堆的实现
堆的实现方式有多种。这里选择笔者认为最简洁实用且性能优越的一种实现方式讲解。
堆可以通过列表的方式实现,列表的索引可以建立父节点与子节点的联系。为了表示方便,将列表的第一个元素(索引为0)定义为None
。还是以二叉最小堆为例,若已知父节点的索引为index
,则左右子节点的索引分别为2 * index
与2 * index + 1
;若已知任意子节点的索引为index
,则父节点的索引为index // 2
。
代码
class Heap(object):
def __init__(self):
self.__keys = [None]
self.__size = 0
def add(self, value):
self.__size += 1
self.__keys.append(value)
self.__go_up(self.__size)
def __go_up(self, index):
if index == 1:
return
parent_index = index // 2
if self.__keys[index] < self.__keys[parent_index]:
self.__swap(index, parent_index)
self.__go_up(parent_index)
def __swap(self, index1, index2):
self.__keys[index1], self.__keys[index2] = self.__keys[index2], self.__keys[index1]
def remove_smallest(self):
self.__keys[1] = self.__keys.pop()
self.__size -= 1
self.__go_down(1)
def __go_down(self, index):
left_child_index = 2 * index
right_child_index = 2 * index + 1
if right_child_index <= self.__size:
if self.__keys[index] > min(self.__keys[left_child_index], self.__keys[right_child_index]):
child_index_swap = left_child_index if self.__keys[left_child_index] < self.__keys[
right_child_index] else right_child_index
self.__swap(index, child_index_swap)
self.__go_down(child_index_swap)
else:
return
elif left_child_index <= self.__size:
if self.__keys[index] > self.__keys[left_child_index]:
self.__swap(index, left_child_index)
self.__go_down(left_child_index)
else:
return
else:
return