LeetCode OJ:Symmetric Tree

Symmetric Tree

 

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

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

算法思想:

迭代实现,两个队列,一个对左子树进行从左到右层序遍历,一个对右子树从右到左层序遍历,每次判断是否相等

/**
 * Definition for binary tree
 * 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 *> ql,qr;
        ql.push(root->left);
        qr.push(root->right);
        while(!ql.empty()){
            TreeNode *curl=ql.front();ql.pop();
            TreeNode *curr=qr.front();qr.pop();
            if(curl==NULL&&curr==NULL)continue;
            if(curl==NULL||curr==NULL||curl->val!=curr->val)return false;
            ql.push(curl->left);ql.push(curl->right);
            qr.push(curr->right);qr.push(curr->left);
        }
        return true;
    }
};

2、递归实现

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool dfs(TreeNode *left,TreeNode *right){
        if(left==NULL&&right==NULL)return true;
        if(left==NULL||right==NULL)return false;
        return left->val==right->val&&dfs(left->left,right->right)&&dfs(left->right,right->left);
    }
    bool isSymmetric(TreeNode *root) {
        if(!root)return true;
        return dfs(root->left,root->right);
    }
};



你可能感兴趣的:(LeetCode)