题解 | #平衡二叉树#

平衡二叉树

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

非递归方式判断平衡二叉树

class Solution {
public:
    bool hasNoChildren(TreeNode* node) {
        if (!node->left && !node->right)
            return true;
        return false;
    }
    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) {
                    if (!hasNoChildren(pre))
                        return false;
                }
                else {
                    if (!hasNoChildren(pro))
                        return false;
                }
            }
            //左右子树都非空
            else {
                q.push(pre->left);
                q.push(pre->right);
                q.push(pro->left);
                q.push(pro->right);
                //如果有一边子树全空,则需要交叉比较所有分支
                if (!pro->left && !pro->right||
                    !pre->left && !pre->right) {
                    q.push(pre->left);
                    q.push(pro->left);
                    q.push(pre->left);
                    q.push(pro->right);

                    q.push(pre->right);
                    q.push(pro->left);
                    q.push(pre->right);
                    q.push(pro->right);
                }
                //如果非全空,则只需要交叉比较不为空的分支
                else {
                    if (pre->left) {
                        if (pro->left) {
                            q.push(pre->left);
                            q.push(pro->left);
                        }
                        if (pro->right) {
                            q.push(pre->left);
                            q.push(pro->right);
                        }
                    }

                    if (pre->right) {
                        if (pro->left) {
                            q.push(pre->right);
                            q.push(pro->left);
                        }
                        if (pro->right) {
                            q.push(pre->right);
                            q.push(pro->right);
                        }
                    }
                }
            }
        }
        return true;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
牛客868257804号:九个中铁八个中建
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务