How to understand function recursion precisely?

前端 未结 4 1089
不知归路
不知归路 2020-12-03 13:08

I am currently programming some divide-conquer algorithms, where function recursions are used everywhere, but I have very vague idea or no idea how exactly it works, and tha

4条回答
  •  借酒劲吻你
    2020-12-03 13:37

    Sometimes it is easier to understand recursion by starting at the base case, that is, the one that does not recurse. In your example, when n<=0, the call is resolved without more calls. Let's start by that.

    If you call Recursion(0), the expected result is to print zero twice, one before and one after the if. The code inside the if does not execute.

    Now, Recursion(1) does its first print of the value one, then calls Recursion(0) which in its turn prints 0 twice like before, then execution returns to Recursion(1), which prints 1 again, after the execution of Recursion(0). That is why you see 1 0 0 1. The same applies to Recursion(2), which will wrap the result of Recursion(1) around twos.

提交回复
热议问题