How does the recursion here work?

后端 未结 9 1138
悲&欢浪女
悲&欢浪女 2021-01-04 12:18

Code 1:

public static int fibonacci (int n){ 
    if (n == 0 || n == 1) { 
        return 1; 
    } else { 
        return fibonacci (n-1) + fibonacci (n-2)         


        
9条回答
  •  逝去的感伤
    2021-01-04 13:00

    Understanding recursion requires also knowing how the call stack works i.e. how functions call each other.
    If the function didn't have the condition to stop if n==0 or n==1, then the function would call itself recursively forever. It works because eventually, the function is going to petter out and return 1. at that point, the return fibonacci (n-1) + fibonacci (n-2) will also return with a value, and the call stack gets cleaned up really quickly.

提交回复
热议问题