leetcode:Symmetric Tree
2016-06-18 22:08
246 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree
But the following
not:
方法二 :
/**
* 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)
{
LinkedList<TreeNode> q=new LinkedList<TreeNode>();
LinkedList<TreeNode> p=new LinkedList<TreeNode>();
q.addLast(root);
p.addLast(root);
while(!q.isEmpty())
{
TreeNode t1=q.remove();
TreeNode t2=p.remove();
if(t1==null&&t2==null)
continue;
if(t1==null||t2==null)
return false;
if(t1.val!=t2.val)
return false;
q.add(t1.left);
q.add(t1.right);
p.add(t2.right);
p.add(t2.left);
}
return true;
}
}
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
/** * 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; return check(root.left,root.right); } public boolean check(TreeNode q, TreeNode p) { if(q==null||p==null) return p==q; return check(q.left,p.right)&&check(q.right,p.left)&&q.val==p.val; } }上述方法采用的是递归的思想; 另一种不用递归的方法下面给出
方法二 :
/**
* 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)
{
LinkedList<TreeNode> q=new LinkedList<TreeNode>();
LinkedList<TreeNode> p=new LinkedList<TreeNode>();
q.addLast(root);
p.addLast(root);
while(!q.isEmpty())
{
TreeNode t1=q.remove();
TreeNode t2=p.remove();
if(t1==null&&t2==null)
continue;
if(t1==null||t2==null)
return false;
if(t1.val!=t2.val)
return false;
q.add(t1.left);
q.add(t1.right);
p.add(t2.right);
p.add(t2.left);
}
return true;
}
}
相关文章推荐
- IOS Dev Intro - Raw Bitmap Modification
- sublime test3 安装quick-cocos2d-x 代码补全插件
- windows,mac 和linux 以及unix
- POJ 3273 Monthly Expense
- django 静态资源共享
- Spring配置bean时id和name的相关讨论
- ActionBar的使用问题
- linux 中的eclipse安装maven
- 从0开始玩安全--Python篇--Python入门指导 & 案例Unixshadow密码破解
- 重载类的特殊方法
- Java - PAT - 1002. 写出这个数 (20)
- 对面向对象的理解及应该了解的问题
- android5.0StateListAnimator
- linux下的文件系统
- 九度OJ 1031
- 信道容量
- 自定义控件起步(二)(自定义属性)
- TP框架基础2
- [bzoj2638] 黑白染色
- 上下左右滑动测试