码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的深度

时间:2014-05-19 13:33:31      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

多的不解释了,这里有两种解法。

第一种:一般的解法

bubuko.com,布布扣
 1 void Deep(BinaryTreeNode* root , int& Maxdeep , int count)
 2 {
 3     if (root->m_pLeft || root->m_pRight)
 4     {
 5         count++;
 6         if (root->m_pLeft)
 7         {
 8             Deep(root->m_pLeft , Maxdeep,count);
 9         }
10         if (root->m_pRight)
11         {
12             Deep(root->m_pRight , Maxdeep,count);
13         }
14         
15     }else //遍历到叶节点
16     {
17         count++;
18         if (count > Maxdeep)
19         {
20             Maxdeep = count ;//保存最大深度
21         }
22     }
23 }
24 int TreeDepth(BinaryTreeNode* root)
25 {
26     int Maxdeep = 0 ;
27     int count = 0 ;
28     Deep(root, Maxdeep, count);
29     return Maxdeep ;
30 }
bubuko.com,布布扣

第二种:大神的解法,代码简洁高效

bubuko.com,布布扣
 1 int TreeDepth(BinaryTreeNode* root)
 2 {
 3     if (root == NULL)
 4     {
 5         return 0 ;
 6     }
 7     int left = TreeDepth(root->m_pLeft);
 8     int right = TreeDepth(root->m_pRight);
 9     return (left > right) ? (left+1) : (right + 1) ;
10 }
bubuko.com,布布扣

 

二叉树的深度,布布扣,bubuko.com

二叉树的深度

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/csxcode/p/3735419.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!