struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int heightOf(TreeNode *n, bool& balanced) {
if (n == NULL) {
return 0;
}
int lh = heightOf(n->left, balanced);
if (!balanced) return -1;
int rh = heightOf(n->right, balanced);
if (!balanced) return -1;
if (lh-rh > 1 || rh-lh > 1) {
balanced = false;
return -1;
}
return (lh>rh? lh: rh)+1;
}
bool isBalanced(TreeNode *root) {
bool balanced = true;
heightOf(root, balanced);
return balanced;
}