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 ofevery node never differ by more than 1.
» Solve this problem
依题意,直接判断左右子树高度差是否不超过1.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
bool balanced = true;
int height(TreeNode *root) {
if (!balanced) {
return -1;
}
if (root == NULL) {
return 0;
}
int lH = height(root->left) + 1;
int lL = height(root->right) + 1;
if (abs(lH - lL) > 1) {
balanced = false;
}
return lH > lL ? lH : lL;
}
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
balanced = true;
height(root);
return balanced;
}
};