struct BinaryTreeNode{
int data;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
//get depth of a binary tree
int Depth(BinaryTreeNode* pRoot){
if(!pRoot) return 0;
if(Depth(pRoot->left)>Depth(pRoot->right))
return Depth(pRoot->left)+1;
else
return Depth(pRoot->right)+1;
}
//solution 1
bool IsBalence(BinaryTreeNode* pRoot){
if(!pRoot) return true;
if(Depth(pRoot->left)-Depth(pRoot->right)>1||
Depth(pRoot->right)-Depth(pRoot->left)>1)
return false;
return IsBalence(pRoot->left)&&IsBalence(pRoot->right);
}
//solution2
bool IsBalence_2Core(BinaryTreeNode* pRoot,int *Depth){
if(!pRoot){
return true;
Depth=0;
}
int left,right;
if(IsBalence_2(pRoot->left,&left)&&IsBalence(pRoot->right,&right)){
if(left-right<1||right-left<1){
Depth=1+(left>right?left:right);
return true;
}
}
return false;
}
bool IsIsBalence_2(BinaryTreeNode* pRoot){
int Depth;
return IsBalence_2Core(pRoot,&Depth);
}