如何计算Java中递归调用的数量?
我用下面给出的方法计算二叉树的高度如何计算Java中递归调用的数量?,java,recursion,Java,Recursion,我用下面给出的方法计算二叉树的高度 int height(Node root) { if (root == null) return 0; else { int lheight = height(root.left); int rheight = height(root.right); if (lheight > rheight) return(lheight+1);
int height(Node root)
{
if (root == null)
return 0;
else
{
int lheight = height(root.left);
int rheight = height(root.right);
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
这将返回lheight=2。起初,我认为lheight在每次递归调用height(root.left)时递增1。但后来我添加了printf语句并再次运行
int height(Node root)
{
if (root == null)
return 0;
else
{
int lheight = height(root.left);
System.out.print(lheight);
int rheight = height(root.right);
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
printf语句打印了此0 1 0 2 0。lheight的值在每次递归调用时是如何变化的?我不是在寻找新的解决方案。我知道这可以通过很多方式实现。我只是想了解这个代码片段中发生了什么。这里是二叉树图像链接。
将计数作为参数传递给方法,最初设置为0或1(取决于您的偏好),然后在每次递归调用该方法时增加计数 编辑:老实说,我还没有测试过这段代码,所以我不知道应该如何更改高度值。感觉这将是无限递归的 无论如何,以下是跟踪递归计数的基本思想:
int height(Node root, int lCount, int rCount)
{
if (root == null){
return 0;
}
else {
int lheight = height(root.left, lCount + 1, rCount);
int rheight = height(root.right, lCount, rCount + 1);
if (lheight > rheight){
return(lheight);
}
else return(rheight);
}
}
使用高度(root,0,0)初始化方法调用,执行的L和R“分支”的最后一次执行应产生各自的总数。您可以创建一个全局变量,该变量在每次函数调用时都会增加
int i; //it has to be initialized with 0
int height(Node root)
{
if (root == null)
return 0;
else
{
i++;
int lheight = height(root.left);
printf("%d ", lheight);
i++;
int rheight = height(root.right);
if (lheight > rheight)
return(lheight);
else return(rheight);
}
}
树的高度是左子树高度和右子树高度的最大值。因此,如果你看到你的代码,那么它会递归地计算左右两个子树的高度,并检查哪个是最大值。如果你真的想可视化它的话。生成被调用方法的树结构。你可以很容易地把它形象化。像这样做-
int height(Node root)
{
if (root == null)
return 0;
else
{
return 1+ Math.max(height(root.left),height(root.right));
}
}
要计算高度,请这样调用
int height = height(root); //this is the height not inside the function
我还没有编译它,但这是获得树的高度的方法(c/c++/java/)举个例子
1
/ \
2 3
/ \
4 5
首先,1将通过它的左边[height(root.left)]调用2。然后2将通过它的左边,所以将调用4。现在4将调用它的左边
由于4没有任何剩余值,它会将null或0传递给lheight。因此,这次代码进入下一步,即函数[height(root.right)]
对于4的右边,我们有null,因此0将返回给rheight。现在借助于
[return(rheight+1);]函数,值1将传递给调用函数2
因此2将lheight设为1。现在2将调用它的right。因此循环继续,2将有两个值l=1和r=1,并将1+1=2返回到它的调用函数,即1
调用1的右边,它将返回1,返回的循环与前面相同。最后,我们有l=2和r=1。因此,我们的最终值为[lheight+1]=3。因此树的高度为3您可以添加一个全局变量,并在函数顶部增加它。这是一个糟糕的长期解决方案,但它会奏效。另外,请只添加相关的标签。这是什么,java还是C++?如果是Java,那么
printf
行可能无法编译。谢谢,但我想知道我是如何得到0 1 0 2 0的,而不仅仅是0 1 2。在某个地方缺少+1。按原样,您的身高应该始终为0。@RustyX抱歉,我编辑了它。是的,我知道,但是lheight的值是如何从0变为1到0到2到0的,如果在最后一次调用中为0,它如何返回2。我认为您需要更改代码1+max(lheight,rHeight),而不是if(lheight>rHeight)返回(lheight);否则返回(rheight);我指的是原始代码失控。我建议的计算递归的方法不是“失控”部分。我会看看我能做些什么,guvnor;-)我已经删除了冒犯性的句子:-p这更好,但仍然是个坏主意:在递归方法中使用要增加的字段;这是因为制造了难以捉摸的虫子。非常糟糕的做法。递归的全部要点是“自包含”