输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
定义:平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
因为子树的左右子树的高度差的绝对值大于1不能使整颗树的左右子树高度差绝对值大于1,所以需要通过遍历的方式将整棵树遍历一遍并检测其左右子树高度差是否大于1。
int TreeDepth(TreeNode* pRoot)
{
if(pRoot){
return max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)) + 1;
}
else{
return 0;
}
}
bool IsBalanced_Solution(TreeNode* pRoot) {
bool flag = true;
if(pRoot){
int h1 = TreeDepth(pRoot->left), h2 = TreeDepth(pRoot->right);
if(abs(h1-h2) > 1)
flag = false;
else{
flag = IsBalanced_Solution(pRoot->right)&& IsBalanced_Solution(pRoot->left);
}
}
return flag;
}