Leetcode101:对称二叉树

题目描述

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

我的解法

利用递归的中序遍历存储每一个节点的值以及此节点属于左节点还是右节点,用pair数据类型存储。然后遍历vector<pair<int, bool>>,判断节点是否对称相等。

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        vector<pair<int, bool>> path;
        inorder(root, path, true);
        
        for(int i=0; i<path.size()/2; i++)
        {
            if(path[i].first != path[path.size()-i-1].first || path[i].second == path[path.size()-i-1].second) return false;
        }       
        return true;
    }
    
    void inorder(TreeNode* root, vector<pair<int, bool>> &path, bool isleft){
        if(!root) return;
        
        inorder(root->left, path, true);
        path.push_back(pair<int, bool> (root->val, isleft));
        inorder(root->right, path, false);
    }
};

其它解法1:递归

对于每一个节点,都找出其对称的节点,判断两值是否相等即可。

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if (!root) return true;
        return isSymmetric(root->left, root->right);
    }
    bool isSymmetric(TreeNode *left, TreeNode *right) {
        if (!left && !right) return true;
        if (left && !right || !left && right || left->val != right->val) return false;
        return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left);
    }    
};

其它解法2:利用队列的非递归遍历

跟上面的思路一样,都是找到其对称的节点,判断是否相等。

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        queue<TreeNode*> q1, q2;
        q1.push(root->left);
        q2.push(root->right);

        while(!q1.empty() && !q2.empty())
        {
            TreeNode* node1 = q1.front(); q1.pop();
            TreeNode* node2 = q2.front(); q2.pop();
            if(!node1 && !node2) continue;
            if((!node1 && node2) || (node1&& !node2) || (node1->val != node2->val)) return false;
            q1.push(node1->left);
            q1.push(node1->right);
            q2.push(node2->right);
            q2.push(node2->left);
        }
        return true;
    }
};
发布了23 篇原创文章 · 获赞 9 · 访问量 1431

猜你喜欢

转载自blog.csdn.net/IcdKnight/article/details/104231278