Leetcode 101. Symmetric Tree
来源:互联网 发布:国家网络应急 编辑:程序博客网 时间:2024/05/17 18:12
题目描述如下:
解决思路:这道题是我在BFS分类中找的,所以就试图用广搜的想法来解决,关键思路就是
1、left对应right
2、left->left对应right->right
3、left->right对应right->left;
技巧就是设立两个队列,一个保存左边的元素,另一个保存右边的元素。
代码如下:
/** * 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 isSameNode(TreeNode* a, TreeNode* b){ if( (!a&&!b) || ((a&&b)&&(a->val==b->val))) return true; else return false; } bool isSymmetric(TreeNode* root) { if(!root) return true; queue<TreeNode*> lqueue; queue<TreeNode*> rqueue; lqueue.push(root->left); rqueue.push(root->right); bool tmp = true; while(!lqueue.empty() && !rqueue.empty()) { TreeNode* lfront = lqueue.front(); TreeNode* rfront = rqueue.front(); lqueue.pop(); rqueue.pop(); if(!isSameNode(lfront, rfront)) { tmp = false; break; } if(lfront) lqueue.push(lfront->left); if(rfront) rqueue.push(rfront->right); if(lfront) lqueue.push(lfront->right); if(rfront) rqueue.push(rfront->left); } return tmp; }};
按照同样的思路,可以写成递归的形式,代码如下:
/** * 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 isSameNode(TreeNode* a, TreeNode* b){ if( (!a&&!b) || ((a&&b)&&(a->val==b->val))) return true; else return false; } bool isSymmetric(TreeNode* root) { if(!root) return true; return isSym(root->left, root->right); } bool isSym(TreeNode* a, TreeNode* b){ if(!isSameNode(a,b)) return false; if(!a&&!b) return true; if(a&&b) return ( (isSym(a->left, b->right)) && (isSym(a->right, b->left))); }};
0 0
- LeetCode 101. Symmetric Tree
- [LeetCode]101.Symmetric Tree
- 【LeetCode】101.Symmetric Tree
- [Leetcode] 101. Symmetric Tree
- LeetCode --- 101. Symmetric Tree
- [leetcode] 101.Symmetric Tree
- LeetCode : 101. Symmetric Tree
- [leetcode]101.Symmetric Tree
- Leetcode 101. Symmetric Tree
- 101. Symmetric Tree LeetCode
- [LeetCode]101. Symmetric Tree
- [LeetCode]101. Symmetric Tree
- [LeetCode]101. Symmetric Tree
- leetcode 101. Symmetric Tree
- LeetCode#101. Symmetric Tree
- Leetcode 101. Symmetric Tree
- Leetcode 101. Symmetric Tree
- LeetCode *** 101. Symmetric Tree
- ssh连不上问题解决办法
- 【腾讯Bugly干货分享】Android 插件技术实战总结
- unity实现简单的加密使用次数限制时间限制功能
- 使用yum安装postgresql 10 dev
- 使用spring注解注入属性
- Leetcode 101. Symmetric Tree
- Hihocoder-1514 偶像的条件
- ROS-roslisp-hello
- error lnk2005解决办法
- 47-将多进程并发服务器改成 IO 复用
- leetcode 20
- 学习笔记之——Android中的Picasso实现圆形头像、圆角图片工具类
- mybatis中<where>标签、<set>标签、<trim>标签、<sql>标签、<foreach>标签的使用
- Activiti数据库配置