劍指offer——二叉樹的深度與平衡二叉樹的判斷

經過後續遍歷,能夠減小重複訪問ios

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 struct BinaryTreeNode
 6 {
 7     int m_data;
 8     BinaryTreeNode* m_left;
 9     BinaryTreeNode* m_right;
10 };
11 
12 int TreeDepth(BinaryTreeNode* pRoot)
13 {
14     if (pRoot==NULL)
15     {
16         return 0;
17     }
18     int nleft=TreeDepth(pRoot->m_left);
19     int nright=TreeDepth(pRoot->m_right);
20     return (nleft>nright)?(nleft+1):(nright+1);
21 }
22 
23 bool IsBalance(BinaryTreeNode* pRoot,int *pDepth)
24 {
25     if (pRoot==NULL)
26     {
27         *pDepth=0;
28         return true;
29     }
30     int left,right;
31     if(IsBalance(pRoot->m_left,&left)&&IsBalance(pRoot->m_right),&right)
32     {
33         int diff=left-right;
34         if (diff<=1&&diff>=-1)
35         {
36             *pDepth=1+(left>right)?left:right;
37             return true;
38         }
39     }
40     return false;
41 }
相關文章
相關標籤/搜索