(写给未来遗忘的自己)
题目:

代码(层次递归:):
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        std::queue<TreeNode*>lefttoright;
        std::queue<TreeNode*>righttoleft;
        if(root==nullptr) return true;
        lefttoright.push(root);
        righttoleft.push(root);
        while(!lefttoright.empty()&&!righttoleft.empty()){
            int layer_size=lefttoright.size();
            for(int i=0;i<layer_size;i++){
                TreeNode* root_left=lefttoright.front();
                TreeNode* root_right=righttoleft.front();
                lefttoright.pop();
                righttoleft.pop();
                
                if(root_left->left==nullptr&&root_right->right!=nullptr) return false;
                if(root_left->left!=nullptr&&root_right->right==nullptr) return false;
                if(root_left->right==nullptr&&root_right->left!=nullptr) return false;
                if(root_left->right!=nullptr&&root_right->left==nullptr) return false;
                if(root_left->left!=nullptr&&root_right->right!=nullptr){
                    if(root_left->left->val!= root_right->right->val) return false;}
            
                if(root_left->right!=nullptr&&root_right->left!=nullptr){
                    if(root_left->right->val!= root_right->left->val) return false;}
               
                if(root_left->left!=nullptr) lefttoright.push(root_left->left);
                if(root_left->right!=nullptr) lefttoright.push(root_left->right);
                if(root_right->right!=nullptr) righttoleft.push(root_right->right);
                if(root_right->left!=nullptr) righttoleft.push(root_right->left);
            }
        }
        return true;
    }
};思路:

利用两个队列,一个队列先放入左树的,一个先放入右树的,这样在一次取的数就是结构上对称的点。
代码(迭代递归)
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        
        if(root==nullptr) return true;
        bool result=check(root->left,root->right);
        return result;
      
    }
    bool check(TreeNode*left,TreeNode*right){
        if(left==nullptr&&right!=nullptr) return false;
         else if(left!=nullptr&&right==nullptr)return false;
         else if(left==nullptr&&right==nullptr) return true;
         else if(left->val!=right->val) return false;
        
         bool outside=check(left->left,right->right);
         bool inside=check(left->right,right->left);
         bool result_t= outside&&inside;
         return result_t;
         
    }
};思路:
将根节点的左右树输入。
直接处理输入的这一对左右数,而不是处理子树,情况可以减少一半。


















