我如何理解堆数据结构中的此删除方法?

问题描述 投票:-1回答:1

给出以下代码:

public Node remove() {
    Node rootNode = heapArray[0]; // set the root node 
    heapArray[0] = heapArray[--currentSize]; // putting the value of the last index in the array at 
    // the 0th index 

    trickleDown(0); // call the trickle down method starting at the 0th index 

    return rootNode; // we return the root node because that will be replaced by another node 
}

private void trickleDown(int idx) { // idx is the index 

    int largerChildIdx; // larger child index 
    Node top = heapArray[idx]; // save last node into top variable ????

    // will run as long as idx is not on the bottom row (has at least 1 child)
    while(idx < currentSize/2) {
        int leftChildIdx = 2*idx +1;
        int rightChildIdx = 2*idx +2;

        // figure out which child is larger
        if(rightChildIdx < currentSize /* check to make sure we are not all the way at the end of the heap
           */ && heapArray[leftChildIdx].getKey() < heapArray[rightChildIdx].getKey()) {
            largerChildIdx = rightChildIdx;
        } else {
            largerChildIdx = leftChildIdx;
        }
        if(top.getKey() >= heapArray[largerChildIdx].getKey()) {
            // successfully made root the largest
            break;
        }
        heapArray[idx] = heapArray[largerChildIdx];
        idx = largerChildIdx; 
    }

    heapArray[idx] = top;

}

我对此行有疑问:

while(idx

为什么idx

java data-structures heap
1个回答
0
投票

在堆中,一半节点是叶节点:没有子节点。因此,如果idx大于或等于节点数的一半,则可以知道该位置的节点没有子级。考虑:

           1
        2     3
       4 5   6   

堆有六个节点。其中三个是叶节点。

如果一个节点没有子节点,那么它已经处于底层:没有理由继续往下滴。

© www.soinside.com 2019 - 2024. All rights reserved.