【LeetCode】100. Same Tree 解题报告
2016-05-30 22:06
441 查看
转载请注明出处:/article/11841695.html
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
方法简单死了~
该方法只是方法一的变形。虽然只是一句话,但是没有方法一结构清晰。
bingo~~
Subject
出处:https://leetcode.com/problems/same-tree/Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
Explain
判断两个二叉树是否一样(结构一样,每个对应的结点的值也是一样)。Solution
solution 1
递归遍历/** * 0ms * * @param p * @param q * @return */ public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null & q == null) { return true; } if (p == null || q == null) { return false; } if (p.val == q.val) { return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } else { return false; } }
方法简单死了~
solution 2
https://leetcode.com/discuss/69708/one-line-java-solutionpublic boolean isSameTree2(TreeNode p, TreeNode q) { return (p != null && q != null && p.val == q.val && isSameTree2(p.left, q.left) && isSameTree2(p.right, q.right)) || (p == null && q == null); }
该方法只是方法一的变形。虽然只是一句话,但是没有方法一结构清晰。
bingo~~
相关文章推荐
- Ubuntu Android Studio快捷方式创建
- 手机开发实战44——手机字符编码介绍2
- 代理模式
- Leetcode 172. Factorial Trailing Zeroes
- Bilinear图像修复
- c++实验6
- 手机开发实战43——手机字符编码介绍1
- LeetCode-199.Binary Tree Right Side View
- 手机开发实战42——手机功能分类
- utf8编码表
- 继承(二)
- R语言实战之高级数据管理
- 算法基础 - 2-sat问题
- gbk编码表
- 第一篇博文
- 安装tushare库
- 关于PDB与DLL
- html5--canvas学习
- Scala隐式转换之隐式参数(1)
- ListView优化整理