数据结构

二叉堆 / 优先队列

向最大堆插入数值并取出最大值。数组和树视图同步更新,展示上浮和下沉过程。

5 分钟难度 2/3交互演示区域不展示广告。
Size7Height3Max90Last actionReady
90708040605030
090170280340460550630

The array is the tree in level order. After every insert or extract, the highlighted nodes show the bubble-up or bubble-down path that restores the max-heap property.

你看到的是什么

1

二叉堆是一棵用数组存储的完全二叉树:i 的子节点在 2i+1 和 2i+2。

2

插入时先放到末尾,然后在新值大于父节点时不断上浮。

3

取出最大值时删除根,把最后一个元素移到顶部,再下沉恢复堆性质。

为什么重要

优先队列是 Dijkstra、A*、任务调度、事件模拟和 Top-K 查询的基础。

复杂度与细节

插入:O(log n)。取出最大值:O(log n)。查看最大值:O(1)。建堆:O(n)。

常见问题

堆是完全有序的吗?+

不是。堆只保证每个父节点不小于其子节点,数组并不是有序的。

为什么用数组存堆?+

完全二叉树没有空洞,可以用下标运算代替指针,缓存更友好、内存更省。