Leetcode_101_Symmetric Tree
来源:互联网 发布:给游戏做美工需要什么 编辑:程序博客网 时间:2024/06/05 22:08
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42087039
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
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.
思路:
(1)题意为判断一棵树是否轴对称。
(2)该题和“判断两棵树是否完全相同”类似,是其强化版,思路大体是一样的。
(3)本文也是采用递归的思想。只要树根不为空,且有左右孩子,则将其左右孩子视为两棵树,本题进行的比较与“判断两棵树是否完全相同”是不一样的,本题比较的是树相反孩子节点的比较,即左孩子与右孩子、右孩子与左孩子的比较,而“判断两棵树是否完全相同”不仅如此,还有左孩子与左孩子、右孩子与右孩子的比较。
(4)希望本文对你有所帮助。
算法代码实现如下所示:
public boolean isSymmetric(TreeNode root) { if(root==null){return true;}else if (root.left == null && root.right == null) {return true;} else if (root.left == null || root.right == null) {return false;} else {if (root.left.val != root.right.val) {return false;} else {return isSameTree(root.left, root.right);}}}public static boolean isSameTree(TreeNode r1, TreeNode r2) {if (r1 == null && r2 == null) {return true;} else if (r1 == null || r2 == null) {return false;} else {if (r1.val != r2.val) {return false;} else {boolean _left = isSameTree(r1.left, r2.right);boolean _right = isSameTree(r1.right, r2.left);if (_left && _right) {return true;} else {return false;}}}}
2 0
- Leetcode_101_Symmetric Tree
- leetcode_101_Symmetric Tree
- leetcode_101_Symmetric Tree
- Tree
- tree
- tree
- TREE
- Tree
- Tree
- tree
- tree
- tree
- tree
- tree
- tree
- Tree
- Tree
- tree
- [leetcode]Permutation Sequence
- HTK 第一章 HTK概要
- 超简单的仿Win8 风格布局,手指按下,背景图片(背景Linearlayout布局)缩小,手指松开恢复。
- 图的邻接表表示
- Linux技术救火命令
- Leetcode_101_Symmetric Tree
- KMP算法C++实现
- readdir仿写ls(1)
- The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar
- HDU 2064 汉诺塔III
- 错题总结
- C++实现的字符串模糊匹配
- 【00】机器学习之旅-启程
- mahout入门指南之基于mahout的itembased算法