[二叉树]leetcode101:对称二叉树(easy)

编程入门 行业动态 更新时间:2024-10-27 00:28:00

[<a href=https://www.elefans.com/category/jswz/34/1769924.html style=二叉树]leetcode101:对称二叉树(easy)"/>

[二叉树]leetcode101:对称二叉树(easy)

题目:

题解1:递归法

class Solution {
public:bool isSymmetric(TreeNode* root) {//if(!root||(!root->left&&!root->right))return true;return check(root->left,root->right);}bool check(TreeNode* p,TreeNode* q){if(!p&&!q)return true;if((!p&&q)||(p&&!q))return false;if(p->val!=q->val)return false;return check(p->left,q->right)&&check(p->right,q->left);}
};

题解2:利用层序遍历迭代法解题

class Solution {
public://解法2:迭代法,利用层序遍历比较左右子树的节点bool isSymmetric(TreeNode* root){if(root==nullptr)return true;queue<TreeNode*> q;q.push(root->left);q.push(root->right);while(!q.empty()){TreeNode *left=q.front();q.pop();TreeNode *right=q.front();q.pop();if(left==nullptr&&right==nullptr)//左右节点皆为空continue;if(left==nullptr||right==nullptr)//左右节点有一个为空return false;if(left->val!=right->val)return false;//节点值不等q.push(left->left);q.push(right->right);q.push(right->left);q.push(left->right);}return true;}
};

更多推荐

[二叉树]leetcode101:对称二叉树(easy)

本文发布于:2023-07-28 18:50:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279335.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:二叉树   对称   easy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!