题解 | 二叉树平衡检查

二叉树平衡检查

https://www.nowcoder.com/practice/b6bbed48cd864cf09a34a6ca14a3976f

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/

#include <algorithm>
#include <complex>
class Balance {
    int check (TreeNode* root){
        if(!root) return 0;
        int lh = check(root->left);
        if(lh == -1) return -1;
        int rh = check(root->right);
        if(rh == -1) return -1;
        if(abs(lh - rh) > 1) return -1;
        return max(lh, rh) +1;       
    }
public:
    bool isBalance(TreeNode* root) {
        // write code here
       return check(root) != -1;
        
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务