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.
AC代码:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(depth(pRoot)==-1)
return false;
return true;
}
int depth(TreeNode* root){
if(root==nullptr)
return 0;
int left=depth(root->left);
int right=depth(root->right);
if(left==-1||right==-1||fabs(left-right)>1)
return -1;
return max(left,right)+1;
}
};