一、题目要求
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.
二、代码实现
bool isBalanced(TreeNode* root) {
if(root==NULL)
return true;
int left=maxDepth(root->left);
int right=maxDepth(root->right);
if(abs(left-right)>1)
return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
int left=1+maxDepth(root->left);
int right=1+maxDepth(root->right);
return left>right?left:right;
}