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

例如,二叉树 [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

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

 


 

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/*
算法思想:
    采用递归方法。
    若都为空树,则对称;若一个空另外一个不空,则不对称;若根节点值不同,则不对称;
*/
//算法实现:
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        return isMirror(root,root);
    }
    bool isMirror(TreeNode* p,TreeNode* q){
        if(!p && !q)
            return true;
        if((!p&&q)||(p&&!q)||(p->val!=q->val))
            return false;
        //这里是关键,就像人站在镜子前审视自己那样。镜中的反射与现实中的人具有相同的头部,但反射的右臂对应于人的左臂,反之亦然。故判断左子树和右子树。    
        return isMirror(p->left,q->right)&&isMirror(p->right,q->left);  
    }
};
/*
算法思想:
    采用迭代方法。
    核心思想和递归一样。若都为空树,则对称;若一个空另外一个不空,则不对称;若根节点值不同,则不对称;
*/
//算法实现:
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();
            TreeNode *node2 = q2.front();
            q1.pop();
            q2.pop();
            if((node1 && !node2) || (!node1 && node2)) 
                return false;
            if (node1) {
                if (node1->val != node2->val) 
                    return false;
                q1.push(node1->left);
                q1.push(node1->right);
                q2.push(node2->right);
                q2.push(node2->left);
            }
        }
        return true;
    }
};