题解 | #JZ79 平衡二叉树#

平衡二叉树

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

//递归获取深度时进行BBT判断

class Solution {
public:
    int depth(TreeNode *pRoot, bool &isBBT) {
        if (!pRoot || !isBBT) return 0;    //节点为空或已非BBT
        
        int leftDepth = depth(pRoot->left, isBBT);    //左子树深度
        int rightDepth = depth(pRoot->right, isBBT);    //右子树深度
        
        if (abs(leftDepth-rightDepth) > 1)    //若深度相差大于1,则不是BBT
            isBBT = false;
        
        return 1 + max(leftDepth, rightDepth);    //子树深度+1为当前树深度
    }
    
    bool IsBalanced_Solution(TreeNode* pRoot) {
        bool isBBT = true;
        
        depth(pRoot, isBBT);    //深度遍历的同时进行BBT判断
        
        return isBBT;
    }
};
全部评论

相关推荐

01-26 18:45
门头沟学院 Java
一天代码十万三:哥们实习再包一下吧,产出太笼统了,尽量体现业务
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务