判断一颗二叉树是否是平衡二叉树

方法一,参考 http://blog.csdn.net/forestlight/article/details/6575507


  1. template<typename T>  
  2. int DepthTree(BSTreeNode<T> *pbs)  
  3. {  
  4.     if (pbs==NULL)  
  5.         return 0;  
  6.     else  
  7.     {  
  8.         int leftLength=DepthTree(pbs->left);  
  9.         int rigthLength=DepthTree(pbs->right);  
  10.         return 1+(leftLength>rigthLength ? leftLength:rigthLength);  
  11.     }  
  12. }  
  13.   
  14. template<typename T>  
  15. bool isBalanceTree(BSTreeNode<T> *pbs)  
  16. {  
  17.     if (pbs==NULL)  
  18.     {  
  19.         return true;  
  20.     }  
  21.       
  22.     int depthLeft=DepthTree(pbs->left);  
  23.     int depthRight=DepthTree(pbs->right);  
  24.       
  25.     if (abs(depthLeft-depthRight)>1)   
  26.          return false;  
  27.     else  
  28.         return isBalanceTree(pbs->left) && isBalanceTree(pbs->right);  
  29. }  

方法一用的是线序遍历的思想, 缺点是,重复计算了多次子树的深度




方法二用的是后序遍历的思想,免去了对子树的重复计算

template<typename T>  
bool isBalanceTree(BSTreeNode<T> *pbs, int &curLen)  
{  
    if (pbs==NULL)  
    {  
        return true;  
    }  
      
    int leftLen;
    int rightLen;
    bool isLeftBalance;
    bool isRightBalance;
	
    leftLen = rightLen = 0;
    isLeftBalance = isRightBalance = false;
	
    isLeftBalance  = isBalanceTree(pbs->left, leftLen);  
    isRightBalance = isBalanceTree(pbs->right, rightLen);  
      
    curLen =  leftLen >= rightLen ?  leftLen+1 : rightLen+1;
	  
    if (isLeftBalance == true && isRightBalance == true)
    {
        if (abs(depthLeft-depthRight) <= 1) 
        {
            return true;
        }
    }	
    return false;
} 


   

你可能感兴趣的:(null)