在最小堆中查找最大元素?

时间:2014-03-28 03:18:58

标签: java algorithm

我现在正在学习堆,显然更多关注堆的min元素,但是我只是想知道如何找到max元素?对于min元素,你只需要返回root,不知道你将如何接近它?

2 个答案:

答案 0 :(得分:5)

我将假设Heap实现为一个数组(这是实现Heap的一种非常常见的方式)。

你不需要检查整棵树,"只有"一半。

因此,如果我从1开始索引数组的元素,那么二进制文件将如下所示(其中数字是数组中的索引):

              1
         2          3
      4    5     6     7
     8 9 10 11 12 13 

你只需要检查floor(length(heapArray)/ 2)最后一个元素,在7以上的情况下,所以从7到13.之前的节点有子节点,所以它们永远不会是最大值。比意味着检查n / 2个元素,因此你仍然有O(n)复杂度。

答案 1 :(得分:-2)

定义变量max并将其初始化为0.

HeapNode[] h;
int last;
int max=0;

如果heap不为空,则从0级和0位置(root)开始,检查最大值并迭代到左右子。

public int getMax() throws Exception {
    if (isEmpty()) {
        Exception EmptyHeapException = new EmptyHeapException();
        throw EmptyHeapException;
    } else {
        //findMax(0, 0);    //If you want to use Iteration
        for(int i=0;i<=last;i++)
            max = Math.max(h[i].key, max);//Updated Thanks Raul Guiu
        return max;
    }
}

每个节点的迭代,直到Node为最后一个。

private void findMax(int i, int level) {
    if (i > last) return;
    if(max<h[i].key)
        max=h[i].key;
    findMax(2*i+1, level+1);//left node
    findMax(2*i+2, level+1);//right node
}

public boolean isEmpty() {
    return (last < 0);
}

您从堆中获得最大值。

相关问题