Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路就是,判断左右子树的高度,是否不超过1
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
return (cntHeight(root) >= 0);
}
int cntHeight(TreeNode *root)
{
if(root == NULL)
return 0;
else
{
int a = cntHeight(root->left);
int b = cntHeight(root->right);
if(a < 0 || b < 0)
return -1;
if((a - b) > 1 || (a-b) < -1)
return -1;
return a>b?(a+1):(b+1);
}
}
};