我从昨天开始就一直在努力让这个函数工作,但它就是不能工作。我什么都试过了。我使用的是一个有深度递归的函数。我得到的输出非常奇怪:
Im going in with depth: 8
Depth in builder: 8
Depth in builder: 7
Depth in builder: 6
Depth in builder: 5
Depth in builder: 4
Depth in builder: 3
Depth in builder: 2
Depth in builder: 1
Depth in builder: 0
Depth in builder: 0
Depth in builder: 0
Depth in builder: 0
Depth in builder: 1
Depth in builder: 0
Depth in builder: 0
Depth in builder: 0
Depth in builder: 0
Depth in builder: 1
.....然后它永远在1和0之间交替。这怎么可能呢?如果深度为0,这条线甚至不会显示。为什么这个一直在继续呢?
如果您想知道,节点的构造函数不会再次调用构建器。构造器没有调用任何外部函数,所以现在它是从那里来的。
发布于 2011-03-18 06:11:48
如果你以最简单的形式来看你的代码(实际上没有做任何事情,只是为了跟踪):
void f(int depth)
{
// print depth
cout << depth << endl;
if(depth <= 0)
return
else
{
// **FOUR** more calls to the recursive function.
f(depth - 1);
f(depth - 1);
f(depth - 1);
f(depth - 1);
}
}现在考虑深度为1的跟踪,您的输出是1 - 0 - 0 - 0,因为每次对f(1)的调用都会生成四个对f(0)的调用。现在考虑一下f(2)的输出--你会得到2 - <output of f(1) four times>。此模式可以扩展,因此您的预期输出是
Output(f(n)) =
n
Output( f(n-1) )
Output( f(n-1) )
Output( f(n-1) )https://stackoverflow.com/questions/5345807
复制相似问题