bool isBalanced(TreeNode *root) {
    bool balancedFlag = true;
    
    isBalancedTree(root, balancedFlag);
    
    return balancedFlag;
}
示例#2
0
/***判断二叉树是否为平衡二叉树***/
int isBalancedTree(BitTree* T, int* depth)
{
	int left, right;
	if(T == NULL)
	{
		*depth = 0;
		return 1;
	}
	if(isBalancedTree(T->lchild, &left) && isBalancedTree(T->rchild, &right))
	{
		int diff = left - right;
		if(diff >= -1 && diff <= 1)
		{
			*depth = (left > right)?(left + 1):(right + 1);
			return 1;
		}
	}
	return 0;
} 
 bool isBalancedTree(TreeNode* root,int& height)
 {
     if(root == nullptr)
     {
         height = 0;
         return true;
     }
     int leftHeight,rightHeight;
     
     bool isLeft = isBalancedTree(root->left,leftHeight);
     bool isRight = isBalancedTree(root->right,rightHeight);
     
     height = max(leftHeight,rightHeight)+1;
     
     if(isLeft && isRight && abs(leftHeight-rightHeight)<=1)
     {
         return true;
     }
     else
         return false;
 }
int isBalancedTree(TreeNode *root, bool &balancedFlag) {
    if (root == nullptr) {
        return 0;
    } else {
        if (balancedFlag) {
            int leftHeight  = isBalancedTree(root->left, balancedFlag);
            int rightHeight = isBalancedTree(root->right, balancedFlag);
            
            if (balancedFlag) {
                if (leftHeight > rightHeight) {
                    balancedFlag = ((leftHeight - rightHeight) <= 1);
                } else {
                    balancedFlag = ((rightHeight - leftHeight) <= 1);
                }
            }
            
            return (1 + std::max(leftHeight, rightHeight));
        } else {
            return 0;
        }
    }
}
 bool isBalanced(TreeNode* root) 
 {
     int i = 0;
     return isBalancedTree(root,i);
     
 }