https://leetcode.com/problems/balanced-binary-tree/description/

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        return abs(getHeight(root->left)-getHeight(root->right))<=1 && isBalanced(root->left) && isBalanced(root->right);
//注意要验证一下是不是左右子树也是balanced
    }

    int getHeight(TreeNode * root){
        if(!root) return 0;
        return 1 + max(getHeight(root->left),getHeight(root->right));
    }
};

results matching ""

    No results matching ""