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
找到左右子树的深度然后比较
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int height(TreeNode * node){
if(node == NULL) return 0;
if(node->left==NULL) return height(node->right)+1;
else if(node->right == NULL) return height(node->left)+1;
else return (height(node->right)>height(node->left)?height(node->right):height(node->left))+1;
}
bool isBalanced(TreeNode *root) {
if(root == NULL) return true;
if(height(root->left)-height(root->right)<=1&&height(root->left)-height(root->right)>=-1){
return isBalanced(root->left)&&isBalanced(root->right);
}
else return false;
}
};