首页 > 代码库 > 【61】101. Symmetric Tree

【61】101. 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;
    }
};

 

 
 
 
 

【61】101. Symmetric Tree