【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是否具有完全相同的 ...
随机推荐
- Oracle-一张表中增加计算某列值重复的次数列,并且把表中其他列也显示出来,或者在显示过程中做一些过滤
总结: 1.计算某列值(数值or字符串)重复的次数 select 列1,count( 列1 or *) count1 from table1 group by 列1 输出的表为:第一列是保留唯一值的 ...
- 类成员函数调用delete this会发生什么呢?
有如下代码 class myClass { public: myClass(){}; ~myClass(){}; void foo() { delete this; } }; int main() { ...
- 11 — springboot集成swagger — 更新完毕
1.前言 理论知识滤过,自行百度百科swagger是什么 2.导入依赖 <!-- swagger所需要的依赖--> <dependency> <groupId>io ...
- 《手把手教你》系列技巧篇(四十八)-java+ selenium自动化测试-判断元素是否可操作(详解教程)
1.简介 webdriver有三种判断元素状态的方法,分别是isEnabled,isSelected 和 isDisplayed,其中isSelected在前面的内容中已经简单的介绍了,isSelec ...
- apostrophe
apostrophe 者,', 0x27, 十进制39,ASCII里的single quote (单引号) 也.one of the 'inverted commas'. 在书写上可以表示所有格.省略 ...
- acclaim
欲学acclaim,先学claim.即使学会claim,未必记住acclaim. [LDOCE] claim的词源是cry out, shoutverb:1. state that sth is tr ...
- 用户名、密码、整数等常用的js正则表达式
1 用户名正则 //用户名正则,4到16位(字母,数字,下划线,减号) var uPattern = /^[a-zA-Z0-9_-]{4,16}$/; //输出 true console.log(uP ...
- SpringMVC注解详情
@Component.@Repository @Service.@Controller 看字面含义,很容易却别出其中三个: @Controller 控制层,就是我们的action层 @Service ...
- bootstrapTable频繁向后台接口发请求
当bootstrapTable出现这样的问题,是因为查询到的数据行数为空,而后台返回的总行数又不为0时,就会疯狂地往接口发请求
- uniapp实现钉钉扫码登录
由于uniapp暂无钉钉授权登录所以本文将钉钉扫码登录作为网页嵌入uniapp,最终实现钉钉扫码登录app 1. 用H5调起钉钉扫码登录 钉钉在网页端的扫码登录可参考钉钉文档:扫码登录第三方网站 - ...