当前位置:网站首页>[LeetCode]572. A subtree of another tree
[LeetCode]572. A subtree of another tree
2022-06-27 21:50:00 【A Fei algorithm】
subject
572. The subtree of another tree
Here are two binary trees root and subRoot . test root Whether and subRoot Subtrees with the same structure and node values . If there is , return true ; otherwise , return false .
Binary tree tree A subtree of includes tree A node of and all descendants of this node .tree It can also be seen as a subtree of its own .
Example 1:
Input :root = [3,4,5,1,2], subRoot = [4,1,2]
Output :true
Example 2:
Input :root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output :false
Tips :
root The number of nodes on the tree ranges from [1, 2000]
subRoot The number of nodes on the tree ranges from [1, 1000]
-104 <= root.val <= 104
-104 <= subRoot.val <= 104
Method 1:dfs
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null || subRoot == null) {
return root == null && subRoot == null;
}
// Be careful , If the comparison is root, Compare the same tree :isSameTree
// If the comparison is root Left and right child nodes , Then compare whether it is a subtree :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);
}
边栏推荐
- Special training of guessing game
- ∫(0→1) ln(1+x) / (x ² + 1) dx
- ICML2022 | 可扩展深度高斯马尔可夫随机场
- MYSQL和MongoDB的分析
- Go from introduction to actual combat - context and task cancellation (notes)
- Go从入门到实战——协程机制(笔记)
- Simulink导出FMU模型文件方法
- 富文本 考试 填空题
- Go from entry to practice - multiple selection and timeout control (notes)
- TypeScript学习
猜你喜欢
让马化腾失望了!Web3.0,毫无希望
Go从入门到实战——Context与任务取消(笔记)
CORBA 架构体系指南(通用对象请求代理体系架构)
跟我一起AQS SOS AQS
PCIE知识点-008:PCIE switch的结构
关于异常处理的知识整理
"Apprendre cette image" apparaît sur le Bureau win11 comment supprimer
Educational Codeforces Round 108 (Rated for Div. 2)
GBase 8a的create database 会被查询耗时很长怀疑卡住的现象分析
A set of system to reduce 10 times the traffic pressure in crowded areas
随机推荐
Educational Codeforces Round 108 (Rated for Div. 2)
Codeforces Global Round 14
Go from introduction to actual combat - package (notes)
豆沙绿保护你的双眼
100 important knowledge points that SQL must master: using functions to process data
跟我一起AQS SOS AQS
Codeforces Round #719 (Div. 3)
空指针异常
小王的面试训练任务
Codeforces Round #723 (Div. 2)
Is it safe to open an account and buy stocks? Who knows
Acwing周赛57-最长连续子序列-(二分or树状数组)
GBase 8a V8版本节点替换期间通过并发数控制资源使用减少对系统影响的方法
Go 访问GBase 8a 数据库的一个方法
动态刷新mapper看过来
ABC-Teleporter Setting-(思维+最短路)
Go从入门到实战——依赖管理(笔记)
IO stream code
ARCS模型介绍
01-Golang-环境搭建