当前位置:网站首页>[LeetCode]572. 另一棵树的子树
[LeetCode]572. 另一棵树的子树
2022-06-27 19:35:00 【阿飞算法】
题目
572. 另一棵树的子树
给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false 。
二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。
示例 1:
输入:root = [3,4,5,1,2], subRoot = [4,1,2]
输出:true
示例 2:
输入:root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
输出:false
提示:
root 树上的节点数量范围是 [1, 2000]
subRoot 树上的节点数量范围是 [1, 1000]
-104 <= root.val <= 104
-104 <= subRoot.val <= 104
方法1:dfs
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null || subRoot == null) {
return root == null && subRoot == null;
}
//注意,如果比较的是root,则比较相同的树:isSameTree
//如果比较的是root左右子节点,则比较的是不是子树 :isSubtree
return isSameTree(root, subRoot) ||
isSubtree(root.left, subRoot) ||
isSubtree(root.right, subRoot);
}
private boolean isSameTree(TreeNode source, TreeNode target) {
if (source == null || target == null) {
return source == null && target == null;
}
return source.val == target.val &&
isSameTree(source.left, target.left) &&
isSameTree(source.right, target.right);
}
边栏推荐
- JVM memory structure when creating objects
- Express e stack - small items in array
- 分享|智慧环保-生态文明信息化解决方案(附PDF)
- oracle迁移mysql唯一索引大小写不区分别怕
- ∫(0→1) ln(1+x) / (x² + 1) dx
- Go from introduction to actual combat - context and task cancellation (notes)
- Full record of 2022 open source moment at Huawei partners and Developers Conference
- Go from starting to Real - Interface (note)
- Have time to look at ognl expressions
- GBase 8a OLAP分析函数cume_dist的使用样例
猜你喜欢

让马化腾失望了!Web3.0,毫无希望

互联网 35~40 岁的一线研发人员,对于此岗位的核心竞争力是什么?

Go從入門到實戰——接口(筆記)

How to delete "know this picture" on win11 desktop

空指针异常

开源技术交流丨一站式全自动化运维管家ChengYing入门介绍

流程控制任务

我想我要开始写我自己的博客了。

After being forced to develop the app within 20 days, the group was laid off, and the technical director angrily criticized it: I wish "closure as soon as possible!"

At 19:00 on Tuesday evening, the 8th live broadcast of battle code Pioneer - how to participate in openharmony's open source contribution in multiple directions
随机推荐
qt 大文件生成md5校验码
100 important knowledge points that SQL must master: sorting and retrieving data
"Apprendre cette image" apparaît sur le Bureau win11 comment supprimer
Go from entry to practice - multiple selection and timeout control (notes)
Set code exercise
今晚战码先锋润和赛道第2期直播丨如何参与OpenHarmony代码贡献
Go from entry to practice -- CSP concurrency mechanism (note)
Yu Wenwen, Hu Xia and other stars take you to play with the party. Pipi app ignites your summer
Flask----应用案例
快速excel导出
Go 访问GBase 8a 数据库的一个方法
我想我要开始写我自己的博客了。
Day8 ---- 云资讯项目介绍与创建
Have time to look at ognl expressions
Go从入门到实战——channel的关闭和广播(笔记)
JVM memory structure when creating objects
01-Golang-环境搭建
OpenSSL 编程 一:基本概念
Scrum和看板的区别
Go从入门到实战——任务的取消(笔记)