查找最大元素在最小堆? [英] Finding max element in a min-heap?

查看:560
本文介绍了查找最大元素在最小堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解的堆,现在显然更注意了堆的最小元素,但我只是想知道你将如何找到最大的元素?对于最小的元素,你就只需要返回根,不知​​道你会如何处理它最大?

I'm learning about heaps right now and obviously more attention is given to the min element of the heap, however I'm just wondering how you would find the max element? For the min element you would just have to return the root, not sure how you would approach it for the max?

推荐答案

定义变量max和它初始化为0。

Define variable max and initialise it to 0.

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

如果堆不为空,从0级和0位置(根)开始,并检查FORMAX价值和迭代左右的孩子。

if heap is not empty,start from 0 level and 0 position(root) and check formax value and iteration to left and right child.

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;
            }
    }

每一个节点,直到节点的迭代是最后一次。

iteration of every node until node is last.

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);
}

你从堆的最大值。

you get maximum value from heap.

这篇关于查找最大元素在最小堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆