101. Symmetric Tree
2016-04-08 14:33
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:
Note:
Bonus points if you could solve it both recursively and iteratively.解法一:
递归方法,判断一个二叉树是否为对称二叉树,对非空二叉树,则如果:
左子树的根val和右子树的根val相同,则表示当前层是对称的。需判断下层是否对称,
此时需判断:左子树的左子树的根val和右子树的右子树根val,左子树的右子树根val和右子树的左子树根val,这两种情况的val值是否相等,如果相等,则满足相应层相等,迭代操作直至最后一层。
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.解法一:
递归方法,判断一个二叉树是否为对称二叉树,对非空二叉树,则如果:
左子树的根val和右子树的根val相同,则表示当前层是对称的。需判断下层是否对称,
此时需判断:左子树的左子树的根val和右子树的右子树根val,左子树的右子树根val和右子树的左子树根val,这两种情况的val值是否相等,如果相等,则满足相应层相等,迭代操作直至最后一层。
bool isSame(TreeNode *root1,TreeNode *root2){ if(!root1&&!root2)//二根都为null, return true; //二根不全为null,且在全部为null时,两者的val不同。 if(!root1&&root2||root1&&!root2||root1->val!=root2->val) return false; //判断下一层。 return isSame(root1->left,root2->right)&&isSame(root1->right,root2->left); } bool isSymmetric(TreeNode* root) { if(!root) return true; return isSame(root->left,root->right); }
相关文章推荐
- app如何保证通讯安全
- [置顶] node-webkit支持sqlite
- Spring源码分析——BeanFactory体系之接口详细分析
- parameter in Inforamtica
- 第一次发博客
- automaticallyAdjustsScrollViewInsets
- 自定义表情输入框
- C# 中使用 OpenSSL 的公钥/私钥进行加密和解密
- Mybatis-Spring-注入映射器
- C++中new 一个对象的时候加括号和不加括号的区别
- 第一个Spring程序-Annotation驱动
- 继承&多态
- 设计模式概述
- 自定义控件--带有删除按钮的EditText
- 对于WAP面试失败的反思
- Java 可以说是产业界和学术界最热门的语言
- Selenium2 Python 自动化测试实战学习笔记
- Oracle数据库用户权限和管理员权限
- css3 transition平滑过渡
- previous_changes方法