2016-04-07 16 views
0
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 
}} 

が試さrecursive.iにこれを変換する方法を取得しておりません多くのウェブサイトが回答を得ていません再帰関数(私は再帰的にこの非再帰的なメソッドを書くことができますどのように)

+1

この質問はC++かjavaについてですか? – user2807083

答えて

2

ループは再帰的メソッド呼び出しに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 
} 
関連する問題