题目:Given a binary tree, determine if it is height-balanced.
判断一棵树是否平衡,要求一个节点的左子树和右子树的深度之差不超过1。立马想到求数的最大深度时用到了左右子树的深度,于是在上面加上一个判断条件即可。
bool balflag=true;
int Balanced(TreeNode *x)
{
if (x == NULL)
return 0;
int leftDepth = Balanced(x->left);
int rightDepth = Balanced(x->right);
if(abs(leftDepth-leftDepth)>1) balflag=false; //左右子树深度差超过1就不平衡
return max(leftDepth, rightDepth) + 1;
}
bool isBalanced(TreeNode *root)
{
Balanced(root);
return balflag;
}