/**
* 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:
int height(TreeNode *root)
{
if(!root)
return 0;
int heightleft = height(root->left);
int heightright = height(root->right);
return max(heightleft, heightright) + 1;
}
bool isBalanced(TreeNode* root) {
if(!root)
return true;
return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
};
/**
* 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:
int height(TreeNode *root)
{
if(!root)
return 0;
int heightleft = height(root->left);
int heightright = height(root->right);
if(heightleft == -1 || heightright == -1 || abs(heightleft-heightright) > 1)
{
return -1;
}
else
{
return max(heightleft, heightright) + 1;
}
}
bool isBalanced(TreeNode* root) {
return height(root) >= 0;
}
};