树的高度

来源:互联网 发布:手机添加网络添加不上 编辑:程序博客网 时间:2024/06/07 06:01

在树的高度计算过程中,我们采用递归算法,从树根算起,先判断树根是否为空,如果树根为空,直接返回0,如果树根不空,遍历左子树,当左子树为空时遍历右子树,具体实现过程:

int maxDepth(TreeNode *root) {

int lh=0,rh=0;

  if(root==NULL) return 0;

else{

 lh=maxDepth(root->left);

 rh=maxDepth(root->right);

    if(lh>rh)

       return lh+1;

   else

       return rh+1;

}

}

原创粉丝点击