题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
Note: 平衡二叉搜索树(Self-balancing binary search tree)具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
class Solution {
public:
bool IsBalanced(TreeNode* pRoot,int* pDepth){
if(pRoot==NULL){
*pDepth=0;
return true;
}
int DepthLeft,DepthRight;
if(IsBalanced(pRoot->left,&DepthLeft)&&IsBalanced(pRoot->right,&DepthRight)){
int diff=DepthLeft-DepthRight;
if(diff>=-1&&diff<=1){
*pDepth=1+(DepthLeft>DepthRight?DepthLeft:DepthRight);
return true;
}
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return IsBalanced(pRoot,&depth);
}
};