Understanding double recursion

前端 未结 3 1561
执笔经年
执笔经年 2021-01-04 20:03

I\'m able to comprehend recursion easily if there is just one recursive call within a function. However, I am really getting confused when I see two or more recursive calls

3条回答
  •  执笔经年
    2021-01-04 20:29

    I'm not sure if I'll be able to explain it very well, but I'll explain it using fibonacci instead. A recursive way for calculating fibonacci numbers are:

    public static int getFib(int n) {
        if(n <= 2) return 1;
        return getFib(n-1)+getFib(n-2);
    }
    

    What actually happens in the code is that it will obviously go down the method calls until it gets a first return. So getFib(n-1) will keep getting called until n <= 2 then it will go back up the method stack and since it now has a value for that getFib(n-1) it will call the getFib(n-2). So say our initial call is with 4, what happens is:

    getFib(4) //Initial call
      getFib(4-1=3) //Left hand recursive call level 1
        getFib(3-1=2) //Left hand recursive call level 2
          return 1 //This would be level 3
        getFib(3-2=1) //Right hand recursive call level 2
          return 1 //level 3
      getFib(4-2=2) //Right hand recursive call level 1
        return 1
    

    Not sure if that makes any sense, this image might visualise it a bit:
    (source: fortystones.com)

    The above code would basically make a depth first (taking the left children first) traversal through that tree.

提交回复
热议问题