如何在java中为堆写一个递归的trickleUp方法?

时间:2013-11-30 03:39:35

标签: java recursion heap

//这是一个堆的trickleup方法,我需要助手为java中的trickleup编写递归方法

public void trickleUp(int index){       
        int parent=(index-1)/2;
        Node bottom=heapArray[index];
        while(index>0 && heapArray[parent].getKey()>bottom.getKey()){
            heapArray[index]=heapArray[parent];
            index=parent;
            parent=(parent-1)/2;             

        }   
        heapArray[index]=bottom;

    } 

2 个答案:

答案 0 :(得分:1)

public void trickleUp(int index, Node bottom){       
        int parent=(index-1)/2;
        if(index>0 && heapArray[parent].getKey()>bottom.getKey()){
            heapArray[index]=heapArray[parent];          
            trickleUp(parent, bottom);
        }   
        else{
          heapArray[index]=bottom;
        }
    } 

答案 1 :(得分:1)

public void trickleUp(int index){
   int parent = (index-1) / 2;
   Node bottom = heapArray[index];

   if(index>0 && heapArray[parent].getKey()>bottom.getKey()){

      swap(index, parent);
      trickleUp(parent);
   }
}