簡體   English   中英

理解這種遞歸方法

[英]Understanding this recursive method

我們正在我的 Java 類介紹中學習遞歸,我很難理解給定示例中的方法是如何工作的。 調用方法時發生了什么?

這是代碼:

public class Hanoi

    private int n;
    private int pegA;
    private int pegB;

    public Hanoi(int in_n, int in_pegA, int in_pegB)
    {
        n = in_n;
        pegA = in_pegA;
        pegB = in_pegB;
    }

    public void makemoves()
    {
        if (n==1)
            System.out.format("%d ==> %d%n", pegA, pegB)
        else
        { 
             int otherPeg = 6 - pegA - pegB; // 1 + 2 + 3 =6
             Hanoi firstmove = new Hanoi (n-1, pegA, otherPeg);
             firstmove.makemoves();
             System.out.format("%d ==> %d%n", pegA, pegB);
             Hanoi secondmove = new Hanoi (n-1, otherPeg, pegB);
             secondmove.makemoves();
        }
    }
}

遞歸只是一種調用自身並測試中斷條件的方法。 這是一個非常簡單的例子來說明基本概念:

static void recurse( int val ) {
    if ( val == 0 ) {
        return; // returns from last invocation
    }
    System.out.println("val=" + val );
    recurse( val - 1 );
    return; // here the method returns to previous invocation (or initial call from main)
}


public static void main( String[] args) {
    recurse( 3 );
}

第一次調用 recurse( 3 ) 調用該方法,在測試 3 != 0 之后,該方法使用 val - 1 調用自身,直到值變為 0。

調用層次結構如下所示:

recurse( 3 )
  recurse( 2 )
    recurse( 1 )
      recurse( 0 ) // break condition
      return        // val == 0
    return          // val == 1
  return            // val == 2
return              // val == 3

這是如何工作的,只需按順序遍歷二叉樹即可。 檢查維基

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM