[抄题]:

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

Example 1:
Given tree s:

     3
/ \
4 5
/ \
1 2

Given tree t:

   4
/ \
1 2

Return true, because t has the same structure and node values with a subtree of s.

Example 2:
Given tree s:

     3
/ \
4 5
/ \
1 2
/
0

Given tree t:

   4
/ \
1 2

Return false.

[暴力解法]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

  1. 两个点直接相等是两棵树相等的特殊情况,下次注意

[思维问题]:

只会写判断树的思路,不知道还有判断点的步骤, 二者需要分开

[一句话思路]:

判断树和判断点分开

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 布尔型函数必须有不在括号中的默认值,注意下
  2. 调用点的traverse也是用的递归

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

  1. 调用点的traverse也是用的递归

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

判断点是否相等:必须要左右都相等才行

public boolean isSame(TreeNode s, TreeNode t) {
//both null
if (s == null && t == null) {
return true;
}
//one is null
if (s == null || t == null) {
return false;
}
//false
if (s.val != t.val) {
return false;
}
//default
return isSame(s.left, t.left) && isSame(s.right, t.right);
}

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
//corner case
if (s == null) {
return false;
}
if (isSame(s,t)) {
return true;
}
return isSubtree(s.left, t) || isSubtree(s.right, t);
} public boolean isSame(TreeNode s, TreeNode t) {
//both null
if (s == null && t == null) {
return true;
}
//one is null
if (s == null || t == null) {
return false;
}
//false
if (s.val != t.val) {
return false;
}
//default
return isSame(s.left, t.left) && isSame(s.right, t.right);
}
}

最新文章

  1. Ajax前台调用后台方法、AJAX Pro2(回调函数)
  2. 学习linux内核时常碰到的汇编指令(1)
  3. [PCL]ApproximateVoxelGrid
  4. bsearch
  5. hihocoder-1391&&北京网赛09 Countries(优先队列)
  6. Handlebars的使用方法文档整理(Handlebars.js)
  7. Decompiled .class file,bytecode version:51.0(Java 7) Source for 'Android API 23 Platform' not found
  8. 使用Texture2D创建Cubemap
  9. ASP.NET MVC 入门介绍 (上)
  10. SQL参数化
  11. 卡特兰数 Catalan数 ( ACM 数论 组合 )
  12. 在 Parallels Desktop 中,全屏模式使用 Win7,唤醒时黑屏
  13. linq中分组查询而且获取每个分组中的第一条记录,数据用于分页绑定
  14. Angularjs 动态创建属性
  15. JavaScript常用函数
  16. Oracle 基本语法、触发器、视图
  17. mysql实践总结
  18. [转]OpenCV2.4.12 开启OpenGL启用三维可视化支持
  19. wordpress配置通过IP直接访问及apache的配置
  20. Codeforces Round #254 (Div. 1) D - DZY Loves Strings

热门文章

  1. phpstudy mysql无法启动
  2. if __name__=="__main__": 这个结尾的理解
  3. 杂项:HTML5-1/3-发展历程
  4. mysql语句求按字段分组后组数是多少
  5. 读取web外的配置文件
  6. 【BZOJ】1912: [Apio2010]patrol 巡逻(树的直径)
  7. Android:ScrollView和SwipeRefreshLayout高度测量
  8. 2、keys相关命令
  9. django使用mysql
  10. Python格式符说明