Leetcode刷题笔记(c++)_剑指 Offer 28. 对称的二叉树

迭代

不容易想到

class Solution {
public:
    bool check(TreeNode* q1,TreeNode* q2){
        if(!q1&&!q2)return 1;
        if(!q1||!q2)return 0;
        return q1->val==q2->val&&check(q1->left,q2->right)&&check(q1->right,q2->left);
    }
    bool isSymmetric(TreeNode* root) {
        return check(root,root);
    }
};

在这里插入图片描述

广度搜索(两个数组记录)

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root==NULL)return 1;
        vector<TreeNode*>temp1;
        vector<TreeNode*>temp2;
        temp1.push_back(root);
        while(!temp1.empty()||!temp2.empty()){
            if(!temp1.empty()){
                int n=temp1.size();
                for(int i=0;i<n;i++){
                    if(temp1[i]==NULL&&temp1[n-1-i]!=NULL)return 0;
                    if(temp1[i]!=NULL&&temp1[n-1-i]==NULL)return 0;
                    if(temp1[i]!=NULL&&temp1[n-1-i]!=NULL){
                        if(temp1[i]->val!=temp1[n-1-i]->val)return 0;
                        temp2.push_back(temp1[i]->left);
                        temp2.push_back(temp1[i]->right);
                    }
                }
                temp1.clear();
            }else{
                int n=temp2.size();
                for(int i=0;i<n;i++){
                    if(temp2[i]==NULL&&temp2[n-1-i]!=NULL)return 0;
                    if(temp2[i]!=NULL&&temp2[n-1-i]==NULL)return 0;
                    if(temp2[i]!=NULL&&temp2[n-1-i]!=NULL){
                        if(temp2[i]->val!=temp2[n-1-i]->val)return 0;
                        temp1.push_back(temp2[i]->left);
                        temp1.push_back(temp2[i]->right);
                    }
                }
                temp2.clear();
            }
        }
        return 1;
    }
};

在这里插入图片描述

广度搜索(一个队列记录)

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root==NULL)return 1;
        queue<TreeNode*>temp1;
        temp1.push(root);
        temp1.push(root);
        while(!temp1.empty()){
            int n=temp1.size();
            for(int i=0;i<n;i=i+2){
                auto q1=temp1.front();
                temp1.pop();
                auto q2=temp1.front();
                temp1.pop();
                if(!q1&&!q2)continue;
                if(!q1||!q2)return 0;
                if(q1->val!=q2->val)return 0;
                temp1.push(q1->left);
                temp1.push(q2->right);

                temp1.push(q1->right);
                temp1.push(q2->left);
            }
        }
        return 1;
    }
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值