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.
根据平衡二叉树的定义,左右子树的最大高度差不超过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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == NULL) return true;
int maxLeft = maxHeight(root->left);
int maxRight = maxHeight(root->right);
if(abs(maxLeft-maxRight) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int maxHeight(TreeNode *root) {
if(root == NULL) return 0;
int maxLeft = maxHeight(root->left);
int maxRight = maxHeight(root->right);
return (maxLeft > maxRight ? maxLeft+1 : maxRight+1);
}
};