题解 | #判断是不是平衡二叉树#

判断是不是平衡二叉树

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pRoot TreeNode类 
 * @return bool布尔型
 */

int depth(struct TreeNode* pRoot){//求树的度
    
    if(pRoot==NULL){
        return 0;
    }
    if(depth(pRoot->left)>depth(pRoot->right))//返回左右子树最大的度+1
        return depth(pRoot->left)+1;
    else 
        return depth(pRoot->right)+1;
}
bool b=true;
bool IsBalanced_Solution(struct TreeNode* pRoot ) {
    // write code here

    if(pRoot==NULL) return true;//如果为空树,则返回true
    if(depth(pRoot->left)>depth(pRoot->right)+1||depth(pRoot->left)<depth(pRoot->right)-1){//判断左右子树的度是否差一
        b=false;
        return b;
    }else{
        IsBalanced_Solution(pRoot->left);
        IsBalanced_Solution(pRoot->right);
    }
    return b;
}

全部评论

相关推荐

06-25 09:33
厦门大学 Java
程序员饺子:现在日常估计没啥hc了,等到八月多估计就慢慢有了。双九✌🏻不用焦虑的
投递快手等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务