- heap是一种特殊的二叉树,始终将最大值或最小值留在二叉树根节点上,分别是MaxHeap和MinHeap实现
- MinHeap与MaxHeap的实现区别在于大小比较相反
- 这里以MaxHeap实现为例,本场景下使用数组操作更方便,所以此处使用数组实现
public class MaxHeap {
private int capacity;
private int size = 1;
private int[] tree;
public MaxHeap(int capacity) {
this.capacity = capacity;
this.tree = new int[capacity];
}
// remove root node and poll new root node
public int poll() {
if(size-1 == 0) throw new NoSuchElementException();
int value = tree[1];
tree[1