ACWING72. 平衡二叉树(剑指offer)

输入一棵二叉树的根结点,判断该树是不是平衡二叉树。

如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

注意:

规定空树也是一棵平衡二叉树。
样例
输入:二叉树[5,7,11,null,null,12,9,null,null,null,null]如下所示,
5
/
7 11
/
12 9

输出:true

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        if(judge(root,1) == -1) return false;
        return true;
    }

    int judge(TreeNode* root,int dep) {
        int Left = dep,Right = dep;
        if(root -> left) Left = judge(root -> left,dep + 1);
        if(root -> right) Right = judge(root -> right,dep + 1);
        if(!root -> left && !root -> right) return dep;
        if(Left == -1 || Right == -1) return -1;
        if(abs(Left - Right) <= 1) return Left + Right;
        else return -1;
    }
};
发布了844 篇原创文章 · 获赞 28 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/tomjobs/article/details/104966397
今日推荐