如何在java中为堆编写递归trickleUp方法?
//这是一个堆的trickleup方法,我需要助手用java编写trickleup的递归方法如何在java中为堆编写递归trickleUp方法?,java,recursion,heap,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()){
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;
}
请阅读:谢谢!我被告知保持方法的接口不变!因此,我尝试了另一种方法,这将工作,但需要和其他交换方法!
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;
}
}
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);
}
}