protected void up-heap(int j) {
while (j > 1) {            // continue until reaching root (or break)
  int p = parent(j);
  if (compare(heap.get(j), heap.get(p)) >= 1) break; // heap property verified
  swap(j, p);
  j = p;                                // continue from the parent's location
}}

如何使用java将非递归代码编写成递归代码。我不知道如何将其转换成递归代码。我尝试了很多网站,但都没有得到答案

最佳答案

关键是将while循环重写为递归方法调用这很简单:

protected void upHeap(int j) {
  if (j <= 1) //this handles the condition of the original while loop
    return;
  int p = parent(j);
  if (compare(heap.get(j), heap.get(p)) >= 1)
    return; // this handles the break from the while loop
  swap(j, p);
  upHeap(p); // the recursive method call, replacing j with p
}

10-06 13:51
查看更多