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 everynode never differ by more than 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int height;
return help(root,hegiht);
}
bool help(TreeeNode *root,int &height){
if(root==NULL)
{
height=0;
return true;
}
int lh,rh;
lh=rh=0;
if(help(root->left,lh ) ==false) return false;
if(help(root->right,rh)==false) return false;
height= lh>rh ? lh+1 : rh+1;
if(abs(lh-rh)>1 )
return false;
else
return true;
}
};