输入一棵二叉树,判断该二叉树是否是平衡二叉树。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
bool res=1;
getHeight(pRoot,res);
return res;
}
int getHeight(TreeNode* root,bool &res){
if(root==NULL)
return 0;
//如果已经判断出不是平衡二叉树了,那就不用再继续再往深里搜索了
if(res==0)
return -1;
else{
int leftHeight=getHeight(root->left,res);
int rightHeight=getHeight(root->right,res);
res=abs(leftHeight-rightHeight)<=1;
return max(leftHeight+1,rightHeight+1);
}
}
};