【剑指Offer】面试题28. 对称的二叉树

题目

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [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

示例 1:

输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:

输入:root = [1,2,2,null,3,null,3]
输出:false

限制:
0 <= 节点个数 <= 1000

本题同【LeetCode】101. 对称二叉树

思路一:递归

利用镜像。

代码

时间复杂度:O(n)
空间复杂度:O(n)

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        return isMirror(root, root);
    }

    bool isMirror(TreeNode *root, TreeNode *copy) {
        if (!root && !copy) return true;
        if (!root || !copy) return false;
        if (root->val == copy->val) {
            return isMirror(root->left, copy->right) && isMirror(root->right, copy->left);
        }
        return false;
    }
};

思路二:迭代

将树的左右节点按相关顺序插入队列中,判断队列中每两个节点是否相等。

代码

时间复杂度:O(n)
空间复杂度:O(n)

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (!root) return true;
        queue<TreeNode*> que;                
        que.push(root);
        que.push(root);
        while (!que.empty()) {
            TreeNode *node1 = que.front();
            que.pop();
            TreeNode *node2 = que.front();
            que.pop();
            if (!node1 && !node2) continue;
            if (!node1 || !node2 || node1->val != node2->val) return false;
            que.push(node1->left);
            que.push(node2->right);
            que.push(node1->right);
            que.push(node2->left);            
        }
        return true;
    }
};

猜你喜欢

转载自www.cnblogs.com/galaxy-hao/p/12359385.html