码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode No101. Symmetric Tree

时间:2016-08-19 11:26:18      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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

判断二叉树是否左右对称

Algorithm:

对左右子树BFS(宽度优先搜索),要注意判断左右子树一个非空一个不为空的情况

Accepted Code:

/**
 * 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==NULL)return true;
        queue<TreeNode*> l;   //左子树
        queue<TreeNode*> r;   //右子树
        if(root->left==NULL&&root->right==NULL)
            return true;
        else if(root->left!=NULL&&root->right!=NULL)
        {
            l.push(root->left);
            r.push(root->right);
        }
        else
            return false;
        while(!l.empty()&&!r.empty())
        {
            TreeNode* temp1=l.front();
            TreeNode* temp2=r.front();
            if(temp1->val!=temp2->val)
                return false;
            l.pop();
            r.pop();
            if(temp1->left&&temp2->right)
            {
                l.push(temp1->left);
                r.push(temp2->right);
            }
            else if((temp1->left==NULL^temp2->right==NULL)==1)
                return false;
            if(temp1->right&&temp2->left)
            {
                l.push(temp1->right);
                r.push(temp2->left);
            }
            else if((temp1->right==NULL^temp2->left==NULL)==1)
                return false;
        }
        if(l.empty()&&r.empty())
            return true;
        else
            return false;
    }
};


leetcode No101. Symmetric Tree

标签:

原文地址:http://blog.csdn.net/u011391629/article/details/52247811

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!