解法一:
class Solution {
public:
bool isBalanced(TreeNode* root) {
return balanceHeight(root)>=0;
}
int balanceHeight(TreeNode* root)
{
if(root==nullptr)
return 0;
int left=balanceHeight(root->left);
int right=balanceHeight(root->right);
if(left<0 || right<0 ||abs(left-right)>1)
return -1;
return max(left,right)+1;
}
};
解法二:
class Solution {
public:
int height(TreeNode *root) {
if(root == NULL)return 0;
return max(height(root->left), height(root->right)) + 1;
}
bool isBalanced(TreeNode* root) {
if(root == NULL)return true;
return isBalanced(root->left) && isBalanced(root->right) && abs(height(root->left) - height(root->right)) <= 1;
}
};