堆结构

  首先介绍树的完整性定义。一棵树满足以下条件时,则称树是完整的:
* 所有的非叶节点都是满的。
* 若底层没有满,则底层的所有节点尽可能靠左。
  以二叉最小堆为例讲解以下内容。一棵二叉树满足以下条件时称为二叉最小堆:
* 树是完整的。
* 所有的子节点不小于父节点。
  对于最小堆结构,remove_smallestadd是两个最常见的操作。

remove_smallest

  拿掉堆最顶部的最小值,为了保持树的完整性,下方的元素需要不断上移,直至二叉最小堆条件重新被满足。

add

  添加节点。实际上,与二叉树不同,二叉最小堆难以从根节点开始查找。因此,添加节点时,直接将新节点添加到底层的最左方以保持树的完整性。然后将该新节点上移直至二叉最小堆条件重新被满足。

堆的实现

  堆的实现方式有多种。这里选择笔者认为最简洁实用且性能优越的一种实现方式讲解。
  堆可以通过列表的方式实现,列表的索引可以建立父节点与子节点的联系。为了表示方便,将列表的第一个元素(索引为0)定义为None。还是以二叉最小堆为例,若已知父节点的索引为index,则左右子节点的索引分别为2 * index2 * 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值