树的高度

xiaoxiao2021-02-28  29

在树的高度计算过程中,我们采用递归算法,从树根算起,先判断树根是否为空,如果树根为空,直接返回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;

}

}

转载请注明原文地址: https://www.6miu.com/read-600306.html

最新回复(0)