判斷二差樹是否爲平衡二叉樹

http://blog.csdn.net/zhaojinjia/article/details/11891523

來自劍指offer

求樹的深度

用遞歸做很簡單,只要知道遞歸出口語句的別寫錯。

  1. struct BinaryTreeNode  
  2. {  
  3.     int m_Value;  
  4.     BinaryTreeNode* m_pLeft;  
  5.     BinaryTreeNode* m_pRight;  
  6. };  
  7.   
  8. int TreeDepth(BinaryTreeNode* pRoot)  
  9. {  
  10.     if (pRoot == NULL)  
  11.         return 0;  
  12.   
  13.     int nLeftDepth = TreeDepth(pRoot->m_pLeft);  
  14.     int nRightDepth = TreeDepth(pRoot->m_pRight);  
  15.   
  16.     return (nLeftDepth>nRightDepth)?(nLeftDepth+1):(nRightDepth+1);  
  17. }  

判斷該樹是否爲平衡二叉樹

方法一:調用上述函數求每個節點的左右孩子深度

  1. bool IsBalanced(BinaryTreeNode* pRoot)  
  2. {  
  3.     if(pRoot== NULL)  
  4.         return true;  
  5.   
  6.     int nLeftDepth = TreeDepth(pRoot->m_pLeft);  
  7.     int nRightDepth = TreeDepth(pRoot->m_pRight);  
  8.     int diff = nRightDepth-nLeftDepth;  
  9.   
  10.     if (diff>1 || diff<-1)  
  11.         return false;  
  12.   
  13.     return IsBalanced(pRoot->m_pLeft)&&IsBalanced(pRoot->m_pRight);  
  14. }  

方法二:由於上述方法在求該結點的的左右子樹深度時遍歷一遍樹,再次判斷子樹的平衡性時又遍歷一遍樹結構,造成遍歷多次。因此方法二是一邊遍歷樹一邊判斷每個結點是否具有平衡性。

  1. bool IsBalanced(BinaryTreeNode* pRoot, int* depth)  
  2. {  
  3.     if(pRoot== NULL)  
  4.     {  
  5.         *depth = 0;  
  6.         return true;  
  7.     }  
  8.   
  9.     int nLeftDepth,nRightDepth;  
  10.     bool bLeft= IsBalanced(pRoot->m_pLeft, &nLeftDepth);  
  11.     bool bRight = IsBalanced(pRoot->m_pRight, &nRightDepth);  
  12.       
  13.     if (bLeft && bRight)  
  14.     {  
  15.         int diff = nRightDepth-nLeftDepth;  
  16.         if (diff<=1 && diff>=-1)  //原文||是錯誤的
  17.         {  
  18.             *depth = 1+(nLeftDepth > nRightDepth ? nLeftDepth : nRightDepth);  
  19.             return true;  
  20.         }  
  21.     }  
  22.       
  23.     return false;  
  24. }  
  25.   
  26. bool IsBalanced(BinaryTreeNode* pRoot)  
  27. {  
  28.     int depth = 0;  
  29.   
  30.     return IsBalanced(pRoot, &depth);  
  31. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章