当前位置:网站首页>[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);
}
边栏推荐
- Go 访问GBase 8a 数据库的一个方法
- Go from introduction to practice -- coordination mechanism (note)
- 跟我一起AQS SOS AQS
- 动态刷新mapper看过来
- Go从入门到实战——共享内存并发机制(笔记)
- 100 important knowledge points that SQL must master: creating calculation fields
- 微服务之远程调用
- 快速excel导出
- Tiktok's interest in e-commerce has hit the traffic ceiling?
- Method of reading file contents by Excel
猜你喜欢

洛谷P5706 再分肥宅水

Go from starting to Real - Interface (note)

White whoring red team goby & POC, how do you call white whoring?

List of language weaknesses --cwe, a website worth learning

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

DO280OpenShift访问控制--security policy和章节实验

How to participate in openharmony code contribution

Go从入门到实战——依赖管理(笔记)

Codeforces Round #717 (Div. 2)

Burp suite遇到的常见问题
随机推荐
Go from introduction to practice -- coordination mechanism (note)
Simulink导出FMU模型文件方法
∫(0→1) ln(1+x) / (x ² + 1) dx
A set of system to reduce 10 times the traffic pressure in crowded areas
Quick excel export according to customized excel Title Template
Use the storcli tool to configure raid. Just collect this article
Go from introduction to practice - polymorphism (note)
uniapp拦截请求
Go从入门到实战——Context与任务取消(笔记)
100 important knowledge points that SQL must master: using functions to process data
关于异常处理的知识整理
SQL必需掌握的100个重要知识点:创建计算字段
Go from entry to practice - dependency management (notes)
开源技术交流丨一站式全自动化运维管家ChengYing入门介绍
TreeSet details
Oracle migration MySQL unique index case insensitive don't be afraid
Galaxy Kirin system LAN file sharing tutorial
Contest 2050 and Codeforces Round #718 (Div. 1 + Div. 2)
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
Is it safe to open an account and buy stocks? Who knows