61101. Symmetric Tree

Posted 会咬人的兔子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了61101. Symmetric Tree相关的知识,希望对你有一定的参考价值。

101. Symmetric Tree

Description Submission Solutions Add to List

  • Total Accepted: 154374
  • Total Submissions: 414598
  • Difficulty: Easy
  • Contributors: Admin

 

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   /   2   2
 / \ / 3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:

    1
   /   2   2
   \      3    3

 

Note:
Bonus points if you could solve it both recursively and iteratively.

 
Solution 1: Recursion
/**
 * 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 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);
    }
};

Solution 2:Iteractive迭代

两个queue实现

/**
 * 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;
        queue<TreeNode*> q1, q2;
        q1.push(root -> left);
        q2.push(root -> right);
        while(!q1.empty() && !q2.empty()){
            TreeNode* top1 = q1.front();
            TreeNode* top2 = q2.front();
            q1.pop();
            q2.pop();
            if((!top1 && top2) || (top1 && !top2)){
                return false;
            }
            if(top1){
                if(top1 -> val != top2 -> val){
                    return false;
                }
                q1.push(top1 -> left);
                q1.push(top1 -> right);
                q2.push(top2 -> right);
                q2.push(top2 -> left);
            }
        }
        return true;
    }
};

 

 
 
 
 

以上是关于61101. Symmetric Tree的主要内容,如果未能解决你的问题,请参考以下文章

101. Symmetric Tree

101. Symmetric Tree

[LeetCode]题解(python):101-Symmetric Tree

Symmetric Tree

[Leetcode] Symmetric Tree

Symmetric Tree