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.
判断一个二叉树是不是平衡二叉树(i.e, 左右子树之差不超过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)
return true;
if(abs(getHeight(root->right)), getHeight(root->left) > 1)
return false;
return isBalanced(root->right)&&isBalanced(root->left);
}
int getHeight(TreeNode* node){
if(!node)
return 0;
return max(getHeight(node->left), getHeight(node->right)) + 1;
}
};