递归调用后使用代码递归

时间:2018-08-13 17:46:41

标签: recursion

我试图理解递归的工作原理,但我还不太了解:在递归函数本身中的递归调用之后,在之后有代码,递归函数如何工作。请在下面的示例伪代码中查看以帮助理解我的意思。 我的确切问题是递归调用之后的代码将以什么顺序执行(意味着何时执行。) 请机器注意递归调用,在调用之后执行其余的代码部分(打印) “ done”),然后返回并实际执行整个递归调用,否则机器将在到达该行后立即执行递归调用,并且仅在递归底部之后才执行最后一段代码(打印“ done”) 什么时候打印?完成多少次?

void recurse()
{
  print "hello world";
  for i = 0 up to 2
    recurse();

  print "done";
}

2 个答案:

答案 0 :(得分:1)

递归调用在其下面的任何代码之前运行。一旦返回,它将返回并完成其余代码。所以发生了什么

"hello world"
i = 0
"hello world"
i = 0
"hello world"
...

永远。因为您没有将i的值传递给下一个递归函数,所以您的代码将永远运行,每次使用i=0重新启动。

让我们假设您确实将i正确传递给了递归函数:

void recurse(i) {
    if (i > 1) {
        print "hello world";
        recurse(i+1);
        print "done";
    }

recurse(0);

在这种情况下,您将得到:

i = 0
"hello world"
    i = 1
    "hello world"
        i = 2
    "done"
"done" 

答案 1 :(得分:1)

可视化递归的一种好方法是使用堆栈的深度/高度。如您所知,每当调用一个新函数时,它将像煎饼一样被推入堆栈,将深度/高度增加1。如果对其进行编码并打印带有缩进的“开始”和“结束”注释以可视化深度,应该很容易看到什么时候执行。如果不清楚,时间在Y轴上(上面打印的东西在下面的东西之前已经执行),递归深度在X轴上。

Here's the code in Python

def recurse(depth=0):
    if depth < 4:
        print("    " * depth + "starting at depth %i" % depth)

        for i in range(2):
            recurse(depth + 1)

        print("    " * depth + "ending at depth %i" % depth)

recurse()

输出

starting at depth 0
    starting at depth 1
        starting at depth 2
            starting at depth 3
            ending at depth 3
            starting at depth 3
            ending at depth 3
        ending at depth 2
        starting at depth 2
            starting at depth 3
            ending at depth 3
            starting at depth 3
            ending at depth 3
        ending at depth 2
    ending at depth 1
    starting at depth 1
        starting at depth 2
            starting at depth 3
            ending at depth 3
            starting at depth 3
            ending at depth 3
        ending at depth 2
        starting at depth 2
            starting at depth 3
            ending at depth 3
            starting at depth 3
            ending at depth 3
        ending at depth 2
    ending at depth 1
ending at depth 0

可以看出,在循环中产生了两个相同的递归调用。循环的第一次行程在第二次行程开始之前完成了其整个递归执行。在两个递归调用完成之后,整个调用结束。

还请注意,深度表示base case或没有子级的终端/叶节点。您原来的算法将无限递归并破坏堆栈。