LeetCode101.对称二叉树

1.题目描述

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

2.示例

LeetCode101.对称二叉树_第1张图片
题目链接:https://leetcode-cn.com/problems/symmetric-tree

3.算法实现

3.1 递归方法

/**
 * 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) {
        if(!root)
            return true;
        return isMirror(root->left,root->right);
    }
    bool isMirror(TreeNode* p,TreeNode* q){
        if(p==NULL && q==NULL){
            return true;
        }
        if(p==NULL || q==NULL){
            return false;
        }
        if(p->val == q->val)
            return isMirror(p->left,q->right) && isMirror(p->right,q->left);
        else
            return false;
    }
};

3.2 迭代法(层次遍历)

/**
 * 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 isMirrorQueue(root);
    }
    bool isMirrorQueue(TreeNode* root){
        queue<TreeNode*>que;
        
        que.push(root);
        que.push(root);
        
        while(!que.empty()){
            TreeNode* t1 = que.front();
            que.pop();
            TreeNode* t2 = que.front();
            que.pop();
            if(t1 == NULL && t2 == NULL)//均为空
                continue;
            if(t1 == NULL || t2 == NULL)//仅一个为空
                return false;
            if(t1->val != t2->val)
                return false;
            que.push(t1->left);
            que.push(t2->right);
            que.push(t1->right);
            que.push(t2->left);
        }
        return true;
    }
};

你可能感兴趣的:(LeetCode)