Recursion 二叉树最大高度的递归代码
我遇到了一个递归代码,用于计算二叉树的最大高度-Recursion 二叉树最大高度的递归代码,recursion,tree,Recursion,Tree,我遇到了一个递归代码,用于计算二叉树的最大高度- int maxDepth(struct node* node) { if (node==NULL) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node->left); int rDepth = maxDepth(node->right); /* use t
int maxDepth(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}
我试着用另一种方式写代码-
int maxDepth(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = 1+maxDepth(node->left); //notice the change
int rDepth = 1+maxDepth(node->right); //notice the change
/* use the larger one */
if (lDepth > rDepth)
return(lDepth);
else return(rDepth);
}
}
我不清楚这两个版本是否工作类似,或者第二个实现中是否存在bug。
我尝试了几个案例,两个函数返回相同的结果。这两个
C
函数的行为相同。重写函数maxDepth()
所做的只是在变量lDepth
和rDepth
中添加1。但是,通过在返回值中从这些变量中减去1,可以有效地撤消该更改:
int lDepth = 1+maxDepth(node->left); // you added one to lDepth
int rDepth = 1+maxDepth(node->right); // you added one to rDepth
/* use the larger one */
if (lDepth > rDepth)
return(lDepth); // but you subtract one here
else return(rDepth); // and you also subtract one here
从算术上讲,它们是相同的,当您将1添加到答案中时,这并不重要,因为没有对返回的值进行其他算术转换。从技术上讲,你的效率稍低,因为你做了两个加法,然后扔掉两个值中较小的一个,这浪费了在那一个上所做的工作。事实上,我怀疑如果你做计时,你是否会注意到差异