通过后续遍历,可以减少重复访问
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 }