二叉树最大高度的递归代码

时间:2015-03-14 14:09:08

标签: 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 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);
   }
} 

我很困惑两个版本是否会起到相似的作用,或者第二个实现中是否存在错误。 我尝试了几个案例,两个函数都返回了相同的结果。

2 个答案:

答案 0 :(得分:0)

算术上它们是相同的,当你将1添加到答案时并不重要,因为没有对返回的值进行其他算术转换。从技术上讲,你的效率稍差,因为你做两次加法,然后扔掉两个值中较小的一个,这会浪费在那一个上完成的工作。实际上,我怀疑你是否注意到了时间差异。

答案 1 :(得分:-1)

这两个C函数的行为相同。您在重写函数maxDepth()时所做的就是向变量lDepthrDepth添加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
相关问题