c++ 对称二叉树 广度优先搜索

class Solution {
public:
    bool isSymmetrical(TreeNode* pRoot)
    {
        if (pRoot == nullptr) return true;
        vector<TreeNode*> tvec;
        tvec.push_back(pRoot);
        while (!tvec.empty()){
            auto length = tvec.size();
            // 检查一层是否镜像 vec中有空节点,不能直接->val
            for (int i = 0; i != length / 2; ++i){
                //一空一不空
                if (tvec[i] == nullptr ^ tvec[length - 1 - i] == nullptr)
                    return false;
                //两个都不空
                else if (tvec[i] != nullptr){
                    if (tvec[i]->val != tvec[length - 1 - i]->val)
                        return false;
                }
            }
            // 更新vec
            for (decltype(length) i = 0; i != length; ++i){
                if (tvec.front() != nullptr){
                    tvec.push_back(tvec.front()->left);
                    tvec.push_back(tvec.front()->right);
                }
                tvec.erase(tvec.begin());
            }
        }
        return true;
    }
};

有参考别人的想法
1、对称的二叉树就是每一层都是对称的,故考虑广度优先搜索
2、因为要用到下标访问,所以用vector、不用queue
3、空树返回true,一开始想反了。

全部评论

相关推荐

06-18 15:03
重庆大学 运营
运营你豪哥:做一下被打的数据,分析输出优化建议
点赞 评论 收藏
分享
05-24 14:12
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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