题解 | #对称的二叉树#

对称的二叉树

https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb


#include<stack>
#include <vector>
class Solution {
public:
    bool isSymmetrical(TreeNode* pRoot) {
	    // 特殊情况
        if (!pRoot) {
            return true;
        }

        if (!pRoot->left && !pRoot->right) return true;

        if (!pRoot->left || !pRoot->right) return false;

        if (!pRoot->left->val || !pRoot->right->val) return false;
		// 一般情况
        auto whole_stack = new stack<TreeNode*>();
        auto currentLevel = new vector<TreeNode*>();
        currentLevel->push_back(pRoot);

        while(!currentLevel->empty())
        {
            auto nextLevel= new vector<TreeNode*>();

            for (auto it = currentLevel->begin(); it != currentLevel->end(); ++it){
                auto left = (*it)-> left;

                if (whole_stack->empty()){
                    whole_stack->push(left);
                } else if (whole_stack->top() == left){
                    whole_stack->pop();
                } else if (!whole_stack->top() || !left){
                    whole_stack->push(left);
                } else if (whole_stack->top()->val ==  left->val){
                    whole_stack->pop();
                } else {
                    whole_stack->push(left);
                }

                auto right = (*it)-> right;

                if (whole_stack->empty()){
                    whole_stack->push(right);
                } else if (whole_stack->top() == right){
                    whole_stack->pop();
                } else if (!whole_stack->top() || !right){
                    whole_stack->push(right);
                } else if (whole_stack->top()->val ==  right->val){
                    whole_stack->pop();
                } else {
                    whole_stack->push(right);
                }

                if (left) {
                    nextLevel->push_back(left);
                }

                if (right) {
                    nextLevel->push_back(right);
                }
            }

            if (!whole_stack->empty()) return false;

            currentLevel = nextLevel;
        }
        return true;
    }
};
  1. 层次遍历
  2. 使用栈记录每一层的对称情况
全部评论

相关推荐

码农索隆:有点耳熟,你们是我教过最差的一届
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 12:05
俺不中了,BOSS遇到了一个hr,我觉得我咨询的问题都很正常吧,然后直接就被拒绝了???
恶龙战士:你问的太多了,要不就整理成一段话直接问他,一个一个问不太好
点赞 评论 收藏
分享
点赞 评论 收藏
分享
06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 14:00
林子大了什么鸟都有啊,我觉得我说的已经很客气了,阴阳谁呢
牛客62656195...:应该不是阴阳吧?你第一次注册的时候boss就说你是牛人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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