描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
注:我们约定空树是平衡二叉树。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if (recur(pRoot) == -1)
return 0;
return 1;
}
int recur(TreeNode* pRoot) {
if (pRoot == nullptr) {
return 0;
}
int nleft = recur(pRoot -> left);
int nright = recur(pRoot -> right);
if(nleft == -1 || nright==-1) {
return -1;
}
if (abs (nleft - nright) > 1) {
return -1;
}
else {
return 1 + max(nleft, nright);
}
}
};