题解 | #平衡二叉树#

平衡二叉树

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

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int leftDeepth = 0;
        int rightDeepth = 0;
      	//空树直接返回true
        if(pRoot == nullptr) return true;
        //左子树不为空时,判断左子树是否为平衡树,若是平衡树求该子树深度,否则为空
        if(pRoot->left != nullptr){
            if( IsBalanced_Solution(pRoot->left) ) 
            {
                leftDeepth = treeDeepth(pRoot->left);
            }else return false;
        }
        //右子树不为空时,判断右子树是否为平衡树,若是平衡树求该子树深度,否则为空
        if(pRoot->right != nullptr){
            if(IsBalanced_Solution(pRoot->right))
            {
                rightDeepth = treeDeepth(pRoot->right);
            }else return false;
        }
        //判断左右子树高度差是否小于等于1
        if(abs(leftDeepth - rightDeepth)<=1) return true;
        else return false;
    }
    //树的深度
    int treeDeepth(TreeNode * pRoot)
    {
        if(pRoot == nullptr) return 0;
        return ( treeDeepth(pRoot->left) > treeDeepth(pRoot->right)? 
                 treeDeepth(pRoot->left) : treeDeepth(pRoot->right) ) + 1;
    }
};
全部评论

相关推荐

2025-11-23 15:33
已编辑
门头沟学院 Java
CUTMR:换账号试试重启推荐算法,我换账号之后回复率还不错,约莫有个20%左右的消息回复率,前几页、主动招呼的HR也开始符合我期望薪资,此前的大号从招呼、回复、前几页的岗位薪资在涨幅30%+以上 用着用着聊着聊着就变成-20%,而且我开通会员之后直接0面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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