Leetcode 101. Symmetric Tree
2016-07-06 21:01
169 查看
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
Note:
Bonus points if you could solve it both recursively and iteratively.
Subscribe to see which companies asked this question
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
if(symmetric(root.left,root.right)){
return true;
}
else{
return false;
}
}
private boolean symmetric(TreeNode left, TreeNode right){
if(left == null && right == null ){
return true;
}
if(left == null || right == null){
return false;
}
if(left.val != right.val){
return false;
}
return (symmetric(left.left,right.right))&&(symmetric(left.right,right.left));
}
}
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
Note:
Bonus points if you could solve it both recursively and iteratively.
Subscribe to see which companies asked this question
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
if(symmetric(root.left,root.right)){
return true;
}
else{
return false;
}
}
private boolean symmetric(TreeNode left, TreeNode right){
if(left == null && right == null ){
return true;
}
if(left == null || right == null){
return false;
}
if(left.val != right.val){
return false;
}
return (symmetric(left.left,right.right))&&(symmetric(left.right,right.left));
}
}
相关文章推荐
- collectd监控应用cpu使用情况
- 程序员的走与留?
- 欢迎使用CSDN-markdown编辑器
- APP开发实战78-Fragment简介
- Mac与Phy组成原理的简单分析
- 习题:codevs 1035 火车停留解题报告
- matlab命令
- [hdu 3652] B-number
- .met mvc 一种判断是否已登录的方式
- 习题:codevs 1035 火车停留解题报告
- 作为前,后端应当了解的Web缓存知识
- logStash收集日志并存储到Elasticsearch
- 单调队列
- 关于在苹果申请邓白氏码的问题
- 位运算求两个数的平均值
- R plot y轴数字刻度改变
- Linux vim Java
- HDU 2524 矩形A + B(有趣递推)
- 【机器学习详解】解无约束优化问题:梯度下降、牛顿法、拟牛顿法
- 位运算求两个数的平均值