【leetcode】Symmetric Tree
2015-07-07 16:09
429 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
思路:判断树是否是对称的 递归判断即可
更简短的写法
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
思路:判断树是否是对称的 递归判断即可
class Solution { public: bool isSymmetric(TreeNode* root) { if(NULL == root) return true; TreeNode * L = root->left; TreeNode * R = root->right; return isSymmetricPart(L, R); } bool isSymmetricPart(TreeNode* L, TreeNode* R) { if(NULL == L && NULL == R) return true; if(NULL == L && NULL != R || NULL == R && NULL != L) return false; if(L->val == R->val) return isSymmetricPart(L->left, R->right) && isSymmetricPart(L->right, R->left); else return false; } };
更简短的写法
class Solution { public: bool isSymmetric(TreeNode* root) { return !root ? true : isSymmetricHelper(root->left, root->right); } bool isSymmetricHelper(TreeNode* left, TreeNode* right) { if (!left && !right) { return true; } return (left && right) && (left->val == right->val) && isSymmetricHelper(left->left, right->right) && isSymmetricHelper(left->right, right->left); } };
相关文章推荐
- Apache2.4.x与Apache2.2.x的一些区别
- linux中如何修改主机名
- GRE写作必备句型
- PHP时间戳代码 上周一等
- 边学边写边进步
- python3.4学习笔记(十七) 网络爬虫使用Beautifulsoup4抓取内容
- Android常用组件
- CentOS6.4搭建mysql高可用架构MHA
- scala实现归并排序
- Python实现合并字典的方法
- 【css实践】清除浮动总结
- 【LeetCode】215. Kth Largest Element in an Array (2 solutions)
- android 编译Launcher3 出错
- 悟空学Linux专栏----第3篇
- MyEclipse6.5安装与卸载SVN插件方法
- MSQL优化基础(height_blanced直方图选择率)
- 虚拟机Q&A
- UINavigationController/导航控制器
- BP算法详谈
- mysql学习