understanding basic recursion

后端 未结 8 2033
public static void main (String[] args)
{
    System.out.println(factorial(5));
}

public int factorial(int n)
{
    if(n <= 1){
        return 1;
    }
    else{         


        
8条回答
  •  情深已故
    2020-11-28 16:27

    1. In the initial call to factorial, n=5, and is pushed on the stack.
    2. Then the else is triggered so 4 is passed to factorial, and is also pushed onto the stack.
    3. Then the else is triggered so 3 is passed to factorial, and is also pushed onto the stack.
    4. Then the else is triggered so 2 is passed to factorial, and is also pushed onto the stack.
    5. Then the else is triggered so 1 is passed to factorial, and is also pushed onto the stack.
    6. Then the else is triggered so 0 is passed to factorial, and is also pushed onto the stack.
    7. The if gets triggered and 1 is returned to the calling factorial.
    8. The if gets triggered and 2 * 1 is returned to the calling factorial.
    9. The if gets triggered and 3 * 2 is returned to the calling factorial.
    10. The if gets triggered and 4 * 3 is returned to the calling factorial.
    11. The if gets triggered and 5 * 4 is returned to the calling factorial.

    The stack also gets cleaned up, however that gets too tedious to type. Essentially all values in a method call are pushed onto the stack, and popped off the stack on the methods return. This keeps them separated between recursive calls.

提交回复
热议问题