【问题标题】:Recursion in finding the height of the tree-what values will be returned to the values that are assigned to recursive calls? [closed]递归查找树的高度 - 哪些值将返回给分配给递归调用的值? [关闭]
【发布时间】:2014-01-06 15:01:42
【问题描述】:
int height(struct node *root)
{
    struct node *temp;
    int ld=-1,rd=-1;

    if(root!=NULL)
    {
        ld=height(root->left);
        rd=height(root->right);

        if(ld>rd)
            return (ld+1);
        else
            return (rd+1);
    }
    else
        return -1;
}

谁能解释局部变量 ld,rd 如何递增并打印树的高度。

【问题讨论】:

  • 画一棵小而重要的树,并用纸上的程序遍历它
  • 我认为你应该学习“演练”的艺术。

标签: c++ c recursion tree


【解决方案1】:

看,你的程序使用递归。它计算左侧和右侧部分的深度,然后检查其中哪个更大。因为,树的总深度将是(1 + ld 或 rd),以较大者为准。
它基本上从一层到另一层,直到它到达NULL 即树的末端。
基本上,这个函数本身是微不足道的,不需要太多解释。
我正在为上述函数提供一个伪代码,它可以帮助你:-

    maxDepth()
    1. If tree is empty then return 0
    2. Else
      (a) Get the max depth of left subtree recursively  i.e., 
          call maxDepth( tree->left-subtree)
      (a) Get the max depth of right subtree recursively  i.e., 
          call maxDepth( tree->right-subtree)
      (c) Get the max of max depths of left and right 
          subtrees and add 1 to it for the current node.
          max_depth = max(max dept of left subtree,  
                         max depth of right subtree) 
                         + 1
       (d) Return max_depth`  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多