/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) {
return true;
}
return checkHeight(root) != INT_MIN;
}
private:
int checkHeight(TreeNode* root) {
if (!root) {
return -1;
}
int left = checkHeight(root->left);
if (left == INT_MIN) {
return INT_MIN;
}
int right = checkHeight(root->right);
if (right == INT_MIN) {
return INT_MIN;
}
int diff = left - right;
if (abs(diff) > 1) {
return INT_MIN;
} else {
return max(left, right) + 1;
}
}
};