我正在尝试理解递归是如何工作的,还有一件事我不太明白:当有代码时,递归函数是如何工作的
之后
递归函数本身内的递归调用。请参见下面的示例伪代码,以帮助理解我的意思。
我确切的问题是,递归调用之后的代码将以什么顺序(即何时)执行。
机器是否会注意到递归调用,在调用之后执行剩余的代码(打印"done"),然后返回并实际执行整个递归调用,或者机器会在到达该行时立即执行递归调用,并在递归触底后只执行最后一段代码(打印"done")?
何时
“完成”会打印多少次?
void recurse()
{
print "hello world";
for i = 0 up to 2
recurse();
print "done";
}
发布于 2018-08-14 02:13:08
可视化递归的一个好方法是使用堆栈的深度/高度。正如你可能知道的,每当一个新函数被调用时,它就像煎饼一样被推到堆栈上,深度/高度增加1。如果你对它进行编码,并用缩进打印"start“和"end”注释以可视化深度,那么应该很容易看到在调用时执行了什么。如果不清楚,时间在Y轴上(上面打印的东西在下面之前执行),递归深度在X轴上。
以下是Python中的代码:
def recurse(depth=0):
if depth < 4:
print(" " * depth + f"starting at depth {depth}")
for _ in range(2):
recurse(depth + 1)
print(" " * depth + f"ending at depth {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
可以看到,在循环中产生了两个相同的递归调用。在第二次循环开始之前,第一次循环完成了它的整个递归执行。在两个递归调用完成后,整个调用结束。
还要注意,深度表示一个
基本情况
(
https://en.wikipedia.org/wiki/Base
案例
(递归%29
)或没有子节点的终端/叶节点。您的原始算法将无限递归并清除堆栈。
发布于 2018-08-14 01:57:12
递归调用在其下面的任何代码之前运行。一旦它返回,它将返回并完成其余的代码。所以发生的事情是
"hello world"
i = 0
"hello world"
i = 0
"hello world"
...
永远。因为您没有传递
到下一个递归函数,您的代码将永远运行,每次使用
..。
让我们假设你确实通过了
到递归函数:
void recurse(i) {
// is i still < 2?
if (i < 2) {
print "hello world";
recurse(i+1);
print "done";
}
recurse(0);
在这种情况下,您将获得:
i = 0
"hello world"
i = 1
"hello world"
i = 2
"done"
"done"
https://stackoverflow.com/questions/51827894
复制相似问题