【LeetCode】572. 另一个树的子树 Subtree of Another Tree(Python & Java)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/subtree-of-another-tree/#/description
题目描述
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.
题目大意
判断 t 是不是 s 的一个子树。
解题方法
方法一:先序遍历
先序遍历把树转成字符串,判断是否为子串。
在当节点为空的时候给一个“#”表示,这样就能表示出不同的子树,因此只需要遍历一次就能得到结果。每次遍历到树的结尾的时候能够按照#区分,另外每个树的节点值之间用","分割。
在提交的时候又遇到一个问题,就是12和2的结果是一样的,那么我在每个遍历结果的开头位置再加上一个逗号就完美解决了。
另外注意,不要判断左右子树不为空再去遍历树,这样就不能添加上“#”了。
Java 代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
StringBuilder spre = new StringBuilder();
StringBuilder tpre = new StringBuilder();
public boolean isSubtree(TreeNode s, TreeNode t) {
preOrder(s, spre.append(","));
preOrder(t, tpre.append(","));
System.out.println(spre.toString());
System.out.println(tpre.toString());
return spre.toString().contains(tpre.toString());
}
public void preOrder(TreeNode root, StringBuilder str){
if(root == null){
str.append("#,");
return;
}
str.append(root.val).append(",");
preOrder(root.left, str);
preOrder(root.right, str);
}
}
方法二:DFS + DFS
要判断一个树 t 是不是另外一个树 s 的子树,那么可以判断 t 是否和树 s 的任意子树是否相等。那么就和100. Same Tree挺像了。所以这个题的做法就是在判断两棵树是否相等的基础上,添加上任意子树是否相等的判断。
判断 t 是否为 s 的子树的方式是:
- 当前两棵树相等;
- 或者,s 的左子树和 t 相等
- 或者,s 的左子树和 t 相等
这三个条件是或的关系。
注意,判断两个树是否相等是与的关系,即:
- 当前两个树的根节点值相等
- 并且,s 的左子树和 t 的左子树相等
- 并且,s 的左子树和 t 的右子树相等
判断是否是子树与是否是相同的树的代码简直是对称美啊~
Python代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if not s and not t:
return True
if not s or not t:
return False
return self.isSameTree(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
def isSameTree(self, s, t):
if not s and not t:
return True
if not s or not t:
return False
return s.val == t.val and self.isSameTree(s.left, t.left) and self.isSameTree(s.right, t.right)
方法三:BFS + DFS
因为 t 的根节点可能对应着 s 中的任意一个节点,那么我们使用 BFS 来遍历 s 的每个节点,然后对每个节点进行判断是否与 t 相等。
Python代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if not s and not t:
return True
if not s or not t:
return False
que = collections.deque()
que.append(s)
while que:
node = que.popleft()
if not node:
continue
if self.isSameTree(node, t):
return True
que.append(node.left)
que.append(node.right)
return False
def isSameTree(self, s, t):
if not s and not t:
return True
if not s or not t:
return False
return s.val == t.val and self.isSameTree(s.left, t.left) and self.isSameTree(s.right, t.right)
日期
2017 年 5 月 9 日
2018 年 10 月 19 日 —— 自古逢秋悲寂寥,我言秋日胜春朝
2018 年 11 月 21 日 —— 又是一个美好的开始
2020年 5 月 7 日 —— 先把工作忙完,再搞其他的
【LeetCode】572. 另一个树的子树 Subtree of Another Tree(Python & Java)的更多相关文章
- LeetCode 572. 另一个树的子树(Subtree of Another Tree) 40
572. 另一个树的子树 572. Subtree of Another Tree 题目描述 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树.s 的一个子树包括 ...
- [程序员代码面试指南]二叉树问题-判断t1树是否包含t2树的全部拓扑结构、[LeetCode]572. 另一个树的子树
题目1 解 先序遍历树1,判断树1以每个节点为根的子树是否包含树2的拓扑结构. 时间复杂度:O(M*N) 注意区分判断总体包含关系.和判断子树是否包含树2的函数. 代码 public class Ma ...
- LeetCode 572. 另一个树的子树 | Python
572. 另一个树的子树 题目来源:https://leetcode-cn.com/problems/subtree-of-another-tree 题目 给定两个非空二叉树 s 和 t,检验 s 中 ...
- Java实现 LeetCode 572 另一个树的子树(遍历树)
572. 另一个树的子树 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树.s 的一个子树包括 s 的一个节点和这个节点的所有子孙.s 也可以看做它自身的一棵子树 ...
- LeetCode 572. 另一个树的子树
题目链接:https://leetcode-cn.com/problems/subtree-of-another-tree/ 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和 ...
- 力扣Leetcode 572. 另一个树的子树
另一个树的子树 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树.s 的一个子树包括 s 的一个节点和这个节点的所有子孙.s 也可以看做它自身的一棵子树. 示例 ...
- [Swift]LeetCode572. 另一个树的子树 | Subtree of Another Tree
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and no ...
- [LeetCode] Subtree of Another Tree 另一个树的子树
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and no ...
- LeetCode算法题-Subtree of Another Tree(Java实现)
这是悦乐书的第265次更新,第278篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第132题(顺位题号是572).给定两个非空的二进制树s和t,检查树t是否具有完全相同的 ...
随机推荐
- R语言与医学统计图形-【10】ggplot2图形映射
ggplot2绘图系统--图形映射 颜色的映射. #aes中映射变量 ggplot()+geom_point(aes(x=carat,y=price,color='blue'),#color视为单一变 ...
- 28-Merge Two Sorted Lists
easy 21. Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new l ...
- Scrapy-Splash的安装和使用
Scrapy-Splash是一个Scrapy中支持JavaScript渲染的工具. Scrapy-Splash的安装分为两部分.一个是Splash服务的安装,具体是通过Docker,安装之后,会启动一 ...
- Spark(四)【RDD编程算子】
目录 测试准备 一.Value类型转换算子 map(func) mapPartitions(func) mapPartitions和map的区别 mapPartitionsWithIndex(func ...
- Scala(八)【面向对象总结】
面向对象总结 面向对象 1.scala包 1.声明包 1.在文件第一行通过package 包名 2.package 包名{ .... } 第二种方法,包名只能在target目录才能看到 2.导入包 1 ...
- C++ 之杂记
今天做了一个题,代码不难,但是编译的时候就恼火,老是报错,也不告诉我错哪了.... 之前的代码是这样的,在main函数中调用这个类的构造函数,就一直报错,但是不知道原因,后来加上了const 就好了. ...
- 用运oracel中的伪列rownum分页
在实际应用中我们经常碰到这样的问题,比如一张表比较大,我们只要其中的查看其中的前几条数据,或者对分页处理数据.在这些情况下我们都需要用到rownum.因此我们要理解rownum的原理和使用方法. Or ...
- 【Java 基础】Java Map中的Value值如何做到可以为任意类型的值
Occasionally the average developer runs into a situation where he has to map values of arbitrary typ ...
- IDEA 使用rest client测试
一.进入 rest 控制台 idea 导航栏 ==> Tools ==> HTTP Client ==> Test RESTFUL Web Service 如图: 一般来说,idea ...
- 【dva】model中effects函数的解析
结构 effects: { *pageQuery({ payload = {} }, { select, call, put }) { const res = yield call(pageQuery ...