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.
判断一个二叉树是否是 height-balaced 的二叉树,height-balaced 二叉树的定义是:任一结点的左右子树高度差不超过1.
/**
* 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==NULL)
return true;
int lh=getHeight(root->left), rh=getHeight(root->right);
if(lh-rh>=-1&&lh-rh<=1)
return isBalanced(root->left)&&isBalanced(root->right);
else
return false;
}
int getHeight(TreeNode* root){
if(root==NULL) return 0;
int l=getHeight(root->left),r=getHeight(root->right);
return l>r?(l+1):(r+1);
}
};