求树的深度,当深度差大于1时不平衡;同时还需要左子树和右子树也是平衡的。

class Solution {
public:
    int height(TreeNode* pRoot){
        if(pRoot==nullptr) return 0;
        int left_h=height(pRoot->left)+1;
        int right_h=height(pRoot->right)+1;
        int h=max(left_h,right_h);
        return h;
    }
    
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot==nullptr) return true;
        int left_height=height(pRoot->left);
        int right_height=height(pRoot->right);
        if(abs(left_height-right_height)>1) return false;
        return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
    }
};