Java 如何理解堆数据结构中的这个删除方法?

Java 如何理解堆数据结构中的这个删除方法?,java,data-structures,heap,Java,Data Structures,Heap,给定以下代码: 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

给定以下代码:

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;

}
公共节点删除(){ Node rootNode=heapArray[0];//设置根节点 heapArray[0]=heapArray[--currentSize];//将数组中最后一个索引的值置于 //第0个索引 trickleDown(0);//从第0个索引开始调用trickleDown方法 return rootNode;//我们返回根节点,因为它将被另一个节点替换 } 私有void trickleDown(intidx){//idx是索引 int largerChildIdx;//较大的子索引 Node top=heapArray[idx];//将最后一个节点保存到top变量???? //只要idx不在最下面一行(至少有一个子项),就会运行 而(idx=heapArray[largerChildIdx].getKey()){ //成功地使root成为最大的 打破 } heapArray[idx]=heapArray[largerChildIdx]; idx=较大儿童idx; } heapArray[idx]=顶部; }
我对这一行有一个问题:

而(idx
为什么它是idx在堆中,一半的节点是叶节点:没有子节点。因此,如果
idx
大于或等于节点数的一半,则知道该位置的节点没有子节点。考虑:

           1
        2     3
       4 5   6   
堆有六个节点。其中三个是叶节点


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

Hi!您可能应该添加一些额外的标记来直接识别编程语言,这将允许更好地搜索此问题,并允许其他人提供所选语言的帮助。