101. Symmetric Tree

来源:互联网 发布:西门子plc编程指令详解 编辑:程序博客网 时间:2024/05/08 19:40

这里写图片描述

第一种方法:非递归,广度优先遍历,用两个队列同时遍历左右子树,判断他们是否是镜像对称

class Solution {public:    bool isSymmetric(TreeNode* root)     {        if(!root)            return true;        queue<TreeNode*>ltree;        queue<TreeNode*>rtree;        if(root->left==NULL&&root->right==NULL)            return true;        else if(root->left==NULL||root->right==NULL)            return false;        else        {            ltree.push(root->left);            rtree.push(root->right);        }        while(!ltree.empty()&&!rtree.empty())        {            TreeNode *lfront=ltree.front();            TreeNode *rfront=rtree.front();            ltree.pop();            rtree.pop();            if(lfront->val!=rfront->val)                return false;            else            {                if(lfront->left==NULL&&rfront->right==NULL)                {}                else if(lfront->left==NULL||rfront->right==NULL)                    return false;                else                {                    ltree.push(lfront->left);                    rtree.push(rfront->right);                }                if(lfront->right==NULL&&rfront->left==NULL)                {}                else if(lfront->right==NULL||rfront->left==NULL)                    return false;                else                {                    ltree.push(lfront->right);                    rtree.push(rfront->left);                }            }        }        return true;    }};

第二种方法:递归,深度优先遍历,判断左子树的左孩子是否等于右子树的右孩子,以及左子树的右孩子是否等于右子树的左孩子。

class Solution {public:    bool isSymmetric(TreeNode* root)     {        if(!root)            return true;        return isSame(root->left,root->right);    }    bool isSame(TreeNode *p,TreeNode *q)    {        if(!p&&!q)            return true;        else if(!p||!q)            return false;        else if(p->val!=q->val)            return false;        else            return isSame(p->left,q->right)&&isSame(p->right,q->left);    }};
0 0
原创粉丝点击