堆的正确定义是什么

What is the correct definition of a heap

我正在阅读 Java 编程中有关堆的内容。在我的教科书上,我找到了堆的定义:堆是一棵完全二叉树,具有以下性质:1)根中的值是树中smallest项; 2) 每个子树都是一个堆

但是当我观看有关堆的视频时,我发现了一个完全不同的堆定义:在堆中,父键 比子键大

现在我很困惑,因为这两个定义不相符。 哪个定义是正确的?

谢谢!

两个定义都正确。

两种Heap

最小堆: 其中父节点总是比其子节点 smaller

最大堆: 其中,父节点总是比其子节点larger

这个 smaller/larger 父项的值比它的子项称为 堆 属性。这Heap Property已被树的每个节点满足。

给定数组 constructing the Heap 的复杂度是 O(n)。这个操作叫做Heapify.

给定一个堆,从堆中 adding/removing 一个 node/element。运算复杂度为O(log(n)).

使用堆数据结构对任意数组进行排序(堆排序)的复杂度为O(n.log(n))。基本上,您从 Min Heap 中提取顶部(根)元素。此操作重复 n 次,因此复杂度为 O(n.log(n))

Quoting wikipedia here

In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: If A is a parent node of B then the key of node A is ordered with respect to the key of node B with the same ordering applying across the heap. A heap can be classified further as either a "max heap" or a "min heap". In a max heap, the keys of parent nodes are always greater than or equal to those of the children and the highest key is in the root node. In a min heap, the keys of parent nodes are less than or equal to those of the children and the lowest key is in the root node. Heaps are crucial in several efficient graph algorithms such as Dijkstra's algorithm, and in the sorting algorithm heapsort. A common implementation of a heap is the binary heap, in which the tree is a complete binary tree (see figure).

有两种类型的堆:

最小堆:父节点总是小于子节点。

Max Heap: 父节点总是大于子节点。