Think of a binary heap as a pile of tangerines:
将二进制堆想像成一堆橘子:
When we want to extract a tangerine from the pile, we grab the top one for a couple of reasons:
当我们要从堆中提取橘子时,出于以下几个原因,我们选择了榜首:
- If we grab a tangerine from the bottom, the pile would collapse. 如果我们从底部抓橘子,那堆就会倒塌。
- The top element is deemed to be the “most valuable”. 最重要的元素被认为是“最有价值的”。
As we go down the pile of fruit, the value or priority of the tangerines decreases.
随着水果的堆积,橘子的价值或优先级降低。
The same idea applies to a binary heap.
同样的想法适用于二进制堆。
Unlike the pile of fruit, a binary heap consists of nodes that each hold a value which could be a number, a string, or an object. Each node has a maximum of 2 children (hence the name “binary heap”), but it is possible for a node to have 1 or no children as shown above.
与水果堆不同,二进制堆由节点组成,每个节点拥有一个值,该值可以是数字,字符串或对象。 每个节点最多可以有2个子节点(因此称为“二进制堆”),但是如上所述,一个节点可以有1个子节点,也可以没有子节点。
As before, we can only extract the topmost element from the heap, which is considered to be of the “highest priority”.
和以前一样,我们只能从堆中提取最高的元素,该元素被认为是“最高优先级” 。
A heap in which all parent nodes are greater than or equal to the children is called a Max-Heap. While a heap in which all parent nodes are less than or equal to the children is called a Min-Heap.
所有父节点大于或等于子节点的堆称为Max-Heap 。 而所有父节点小于或等于子节点的堆称为Min-Heap 。
It is important to note that a binary heap should always be a complete binary tree. This means that at every level, except possibly the last, all nodes are completely filled, and all nodes are as far left as possible.
重要的是要注意, 二进制堆应该始终是完整的二进制树 。 这意味着,除了最后一个级别外,在每个级别上,所有节点都被完全填充,并且所有节点都尽可能地靠左。
An Example of a complete binary tree:
完整的二叉树的示例:
Example of an incomplete binary tree:
不完整的二叉树的示例: