int Maxhigh(struct TreeNode *root){//计算树高
if(root==NULL)
return 0;
else{
int left=Maxhigh(root->left)+1;
int right=Maxhigh(root->right)+1;
return left>right?left:right;
}
}
bool isBalanced(struct TreeNode* root){
if(root==NULL)
return true;
else{
int height=Maxhigh(root->left)-Maxhigh(root->right);//左右子树高的差
return (height>=-1)&&(height<=1)&&isBalanced(root->left)&&isBalanced(root->right);
//递归调用,判断该层树高的差是否在[-1,1]内,还有子树是否同样满足要求,如果都满足说明平衡
}
}
Leetcode第110题平衡二叉树||C语言
最新推荐文章于 2024-06-12 10:00:23 发布