【leetcode】【101】Symmetric Tree
2016-03-04 10:38
507 查看
一、问题描述
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
二、问题分析
无非还是树的遍历问题。只不过与传统的先序、中序、后序、层次等不太一样。首先空树符合条件,只有根节点也符合,然后判断根节点的左孩子和右孩子,然后递归遍历。需要注意的是,递归的node的左右。三、Java AC代码
public boolean isSymmetric(TreeNode root) {if (root == null) {
return true;
}
return isSymmetricTree(root.left, root.right);
}
public boolean isSymmetricTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val == q.val && isSymmetricTree(p.left, q.right)
&& isSymmetricTree(p.right, q.left);
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树