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

2023-09-11 06:08:43 作者:泪也成诗

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

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.