【一天一道LeetCode】#101. Symmetric Tree
2016-06-25 22:40
459 查看
一天一道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(一)题目
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
Note:
Bonus points if you could solve it both recursively and iteratively.
(二)解题
本题大意:判断一颗树是不是左右对称解题思路一:分别求二叉树的前序和后序遍历,他们是互为反转数组。
/** * 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) { vector<int> pre; vector<int> post; preOrderTree(root , pre); postOrderTree(root , post); for(int i = 0 ,j=post.size()-1; i<pre.size(),j>=0;i++,j--)//一个正向,一个反向 { if(pre[i] != post[j]) return false;//不相等就返回false } return true; } void preOrderTree(TreeNode* root , vector<int> &pre)//前序遍历 { if(root==NULL) {pre.push_back(0);return;} pre.push_back(root->val); preOrderTree(root->left,pre); preOrderTree(root->right,pre); } void postOrderTree(TreeNode* root , vector<int> &post)//后续遍历 { if(root==NULL) {post.push_back(0);return;} postOrderTree(root->left,post); postOrderTree(root->right,post); post.push_back(root->val); } };
解题思路二:将前序遍历和后序遍历合起来一起考虑,对于一个节点,如果他们相等,就判断左右子树是否为镜像!
/** * 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) { return isMirror(root,root); } bool isMirror(TreeNode* root1,TreeNode* root2) { if(root1==NULL) return root2==NULL; if(root2==NULL) return false; if(root1->val!=root2->val) return false; return isMirror(root1->left,root2->right) && isMirror(root1->right,root2->left);//左子树和右子树是否成镜像 } };
相关文章推荐
- 【转载】假如我是计算机系老师
- 【转载】TCP/IP 之 大明王朝邮差
- centos 搭建C++开发环境(gbk编码)
- 修改注册表权限Regini
- xml文档的查询
- 从多地疫苗被质疑事件 看预防接种互联网化之急
- HTML5与移动端web学习笔记
- 【转载】我是一个线程(修订版)
- CXF 自定义拦截器
- c++设计模式之单例模式下的实例自动销毁(垃圾自动回收器)
- c,c++中字符串处理函数strtok,strstr,strchr,strsub
- 【转载】我是一个网卡
- leetcode---Combinations
- 打字
- 我的常用-正则表达式(邮箱验证)
- EIDE助手开始内测辣~~
- 函数表达式
- 【转载】CPU阿甘
- Sitemesh Demo
- 安卓开发之使用DashPathEffect来绘制虚线