Symmetric Tree
来源:互联网 发布:com域名删除的准确时间 编辑:程序博客网 时间:2024/05/16 08:06
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
第一种方法:不使用递归
只要保证根节点下的左子树的每一层是右子树的镜像,就可以说明此树是其自身的镜像
思路:用两个队列饭别记录左右子树每一层的节点,在广度优先遍历左右子树时,为了方便比较左右两边的节点,也把空节点加入到队列中。针对两边镜像节点的情况,必须处理如下不同的情况
(1)如果两边节点均为空,忽略这种情况;
(2)如果一边为空而另一边不为空,则返回false;
(3)如果两者均不为空,但值不相同,则返回false;
(4)除了以上三种情况。第四种情况为把左边的节点的子节点按照从左到右顺序加入到左边的队列尾部,而把右边的节点的子节点按照从右到左顺序加入到右边的队列尾部。其理由是方便用从头部到尾部的顺序比较两个队列是否为镜像关系、
在广度优先遍历完成之后,还需要判断两个队列是否均为空,只有均为空才返回真
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) return true;//使用两个队列分别记录左右子树的每一层节点Queue<TreeNode> left = new LinkedList<TreeNode>();Queue<TreeNode> right = new LinkedList<TreeNode>();left.add(root.left);right.add(root.right);while (!left.isEmpty() && !right.isEmpty()) {//将两个队列的头部列出TreeNode l = left.poll();TreeNode r = right.poll();//忽略两者为空的情况if (l == null && r == null) {continue;}//一方为空,返回falseif (l == null || r == null) {return false;}if (l.val != r.val) {return false;}left.add(l.left);left.add(l.right);//反过来插入right.add(r.right);right.add(r.left);}//遍历完之后,比较两队列的元素个数if (left.isEmpty() && right.isEmpty()) {return true;} else {return false;}}}
第二种方法:使用递归
public boolean isSymmetric(TreeNode root) { return isMirror(root, root);}public boolean isMirror(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) return true; if (t1 == null || t2 == null) return false; return (t1.val == t2.val) && isMirror(t1.right, t2.left) && isMirror(t1.left, t2.right);}
0 0
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- 数据库系统工程师
- AngularJs ng-change事件/指令
- ViewPager高度自适应
- 【测试】软件测试流程进阶----两年软件测试总结
- 学习MySQL_第三天_语言基础&数据定义功能
- Symmetric Tree
- Android中常用的五种布局方式:LinearLayout
- 第3周项目1 -顺序表的基本运算
- CVE-2016-4655 windknown
- 欢迎使用CSDN-markdown编辑器
- openssl制作证书的过程
- Example of Reveal animations on Android 5.0
- export,echo
- 将mysql中查询出来的数据 序列化到protobuffer消息结构体中