本文介绍了递归如何在下面的代码中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是计算二叉树的高度/深度的代码。

This is the code to calculate height/depth of binary tree.

int maxDepth(struct node * node)
{
    int lheight,rheight;
     if(node==NULL)
     return 0;

     lheight=maxDepth(node->left);
     rheight=maxDepth(node->right);
     printf("%d %d\n",lheight,rheight);
     if(lheight>rheight)
     return (lheight+1);
     else
     return (rheight+1);
}





执行此代码时我得到一个输出

0 0

1 0

0 0

0 1

2 2



和最终答案是3

上面的代码中没有添加,返回的值是0我们如何获得1或2作为输出,任何人都可以解释这一点。谢谢。



when this code is executed i get a output
0 0
1 0
0 0
0 1
2 2

and final answer is 3
there is no addition in the above code and the value returned is 0 how are we getting 1 or 2 as output , can anybody explain this. Thank You.

推荐答案

n! = n * (n - 1)!   where n > 0



这意味着当n大于零(因此它有一个有效的终止符来停止执行)时,您可以通过将数字乘以系数的阶乘来计算阶乘。数字少一个:


Which means that while n is greater than zero (so it has a valid terminator to stop execution) you can calculate a factorial by multiplying the number by the factorial of the number less one:

5! = 5 * (5-1) * (5 - 1 - 1) * (5 - 1 - 1 - 1) * (5 - 1 - 1 - 1 - 1)





您的代码以相同的方式工作:它通过在每一侧使用它自己的代码来计算每一方的深度,然后在每个阶段它返回最大的(加一个来计算级别)。

因此,如果一个节点没有子节点,它将返回1(因为函数顶部的测试返回0作为不存在的节点的深度)。



这可能意义不大,所以在纸上绘制节点结构的地图,如下所示:



Your code works in the same way: it works out the depth of each side by using it's own code on each side, then at each stage it returns the largest (plus one to count that level).
So if a node has no sub-nodes, it will return 1 (because the test at the top of the function returns 0 as the depth of non-existent nodes).

That probably doesn't mean much, so draw on paper a "map" of your node structure like this:

  A
 / \
B  C
  / \
 D   E
  \
   F

然后走路它通过手动,或使用调试器一步一步地运行它,同时查看地图。



在某些时候BING!时刻应该发生,它才有意义!

And then either "walk it through" manually, or use the debugger to run it step by step, looking at the map at the same time.

At some point the "BING!" moment should happen and it'll make sense!


这篇关于递归如何在下面的代码中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:47
查看更多