[leetcode]Symmetric Tree
2015-12-11 11:20
323 查看
题目描述如下:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
判断一棵树是否为对称的
一般树的题目本人喜欢用递归实现,在每个子树中考虑以下几种情况:
1、一棵树是否对称与根节点无关,而与左右节点有关,所以接下来的判断都是针对两个节点;
2、如果左右节点都为空,返回true;
3、若两个节点只有一边为空,返回false;
4、若两个节点值相等,返回true;
5、若两个节点值不相等,递归判断左节点的右子树与右节点的左子树是否相等以及左节点的左子树和右节点的右子树是否相等
题中的案例是一个不粗的提示可以判别算法是否正确。代码如下:
题目链接:https://leetcode.com/problems/symmetric-tree/
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
判断一棵树是否为对称的
一般树的题目本人喜欢用递归实现,在每个子树中考虑以下几种情况:
1、一棵树是否对称与根节点无关,而与左右节点有关,所以接下来的判断都是针对两个节点;
2、如果左右节点都为空,返回true;
3、若两个节点只有一边为空,返回false;
4、若两个节点值相等,返回true;
5、若两个节点值不相等,递归判断左节点的右子树与右节点的左子树是否相等以及左节点的左子树和右节点的右子树是否相等
题中的案例是一个不粗的提示可以判别算法是否正确。代码如下:
public class Solution { public boolean isSymmetric(TreeNode root) { if(root == null) return true; return jugdement(root.left, root.right); } public boolean jugdement(TreeNode node1, TreeNode node2){ if(node1 == null && node2 == null) return true; else if(node1 == null || node2 == null) return false; if(node1.val != node2.val) return false; else return jugdement(node1.left, node2.right) && jugdement(node1.right, node2.left); } }
题目链接:https://leetcode.com/problems/symmetric-tree/
相关文章推荐
- jsp页面格式化
- PyQt5 学习笔记
- 黑马程序员——Java之多线程(下)
- 在Liunx中出现yum问题
- nginx 的安装
- 软件测试中JMeter和Ant实现自动负载测试
- 物理引擎介绍
- 关于图的割点
- js获取键盘按键的值
- linux 安装nginx
- aop之应用 时间记录器及日志
- JS event使用方法详解
- Exchange2010 owa 访问 http 500 内部服务器错误
- 发现梦想离自己越来越远了
- 基于JSPatch的iOS应用线上Bug的即时修复方案,附源码.
- event对象获取方法总结在google浏览器下测试
- 编译Spark 1.5.2
- 在Servlet3.0中使用request.getParts()获取上传文件
- oracle数据库中的联接查询
- table中th高度设置无效