leetcode No101. Symmetric Tree

来源:互联网 发布:linux 查看显卡型号 编辑:程序博客网 时间:2024/06/05 02:53

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;    }};


0 0