计算树高的函数

时间:2019-11-29 17:12:14

标签: c++ recursion

我在努力理解下面的maxDepth函数来计算树的高度是如何工作的。

考虑树:

       1
      / \
     2   3
    / \
   4   5
        \
         8

在下面的代码中,当我们使用参数maxDepth调用root函数时,实际上是在计算什么?

我们声明两个变量:

int lDepth = maxDepth(node->left);  
int rDepth = maxDepth(node->right); 

因此我们为root分配:

int lDepth = maxDepth(2);  
int rDepth = maxDepth(3); 

但是这里没有实际的数值,那么如何在此下方调用if (lDepth > rDepth)?没有什么可以实际比较其中的值吗?我本以为if语句中的代码不应该执行。

#include <iostream>
using namespace std; 

class node  
{  
    public: 
    int data;  
    node* left;  
    node* right;  
};  

int maxDepth(node* node)  
{  
    if (node == nullptr)  
        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);  
    }  
}  

node* newNode(int data)  
{  
    node* Node = new node(); 
    Node->data = data;  
    Node->left = nullptr;  
    Node->right = nullptr;  

    return(Node);  
}  

int main()  
{  
    node *root = newNode(1);  

    root->left = newNode(2);  
    root->right = newNode(3);  
    root->left->left = newNode(4);  
    root->left->right = newNode(5);  
    root->left->right->right = newNode(8);  

    cout << "Height of tree is " << maxDepth(root);  
    return 0;  
}  

2 个答案:

答案 0 :(得分:0)

  

我们声明两个变量:

int lDepth = maxDepth(node->left);  
int rDepth = maxDepth(node->right); 
     

所以对于根,我们要分配:

int lDepth = maxDepth(2);  
int rDepth = maxDepth(3);

不。相反,我们正在寻找两棵树的深度

  2
 / \
4   5
     \
      8

3

答案 1 :(得分:0)

maxDepth()是一个递归函数。因此,在第二级(比根低一级),有两个节点23

首先查看node 3maxDepth(3)将进行分配并调用自身,然后检查是否有指针,因为没有指针,它将从

返回0。
if (node == nullptr)  
        return 0; 

因此rDepth为0,而node为3。

类似地,对于node 2,它会执行相同的操作,并带有多个自调用,并将一个整数分配给lDepth

maxDepth()视为对象而不是函数可能会有所帮助。