题解 | #扑克牌顺子#

平衡二叉树

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

非递归方式

class Solution {
public:
    bool hasNoChildren(TreeNode* node) {
        if (!node->left && !node->right)
            return true;
        return false;
    }
    int getHeight(TreeNode* root){
        if(root == NULL) return 0;//如果节点为空高度为0
        int lh = getHeight(root->left);//返回左子树高度
        int rh = getHeight(root->right);//返回右子树高度
        return max(lh,rh) + 1;    //取左子树和右子树高度中最大的并且+1
    }
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if (!pRoot) return true;
        queue<TreeNode*> q;
        q.push(pRoot->left);
        q.push(pRoot->right);
        while (!q.empty()) {
            TreeNode* pre = q.front();
            q.pop();
            TreeNode* pro = q.front();
            q.pop();
            //左右子树都为空
            if (!pre && !pro) continue;
            //左右子树只有一个是空
            if (!pre || !pro) {
                if (pre)
                    return hasNoChildren(pre);
                return hasNoChildren(pro);
            }
            //左右子树都非空
            else {
                if(!pre->left && !pre->right || 
                   !pro->left && !pro->right)
                    return abs(getHeight(pre)-getHeight(pro))<=1;
                q.push(pre->left);
                q.push(pre->right);
                q.push(pro->left);
                q.push(pro->right);
            }
        }
        return true;
    }
};


全部评论

相关推荐

07-09 19:25
门头沟学院 Java
这是要把每一个投校招的都开盒吗?
26届之耻将大局逆转:裁人的时候一次性追回餐费
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:15
点赞 评论 收藏
分享
每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
一表renzha:手写数字识别就是一个作业而已
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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