当前位置:网站首页>[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 from introduction to practice - Interface (notes)
- Array assignment
- GBase 8a OLAP分析函数 cume_dist的使用样例
- Quick excel export
- 强制 20 天内开发 APP 后集体被裁,技术负责人怒批:祝“早日倒闭!”
- CEPH distributed storage
- Codeforces Round #722 (Div. 2)
- List of language weaknesses --cwe, a website worth learning
- 农产品期货怎么做怎么开户,期货开户手续费多少,找谁能优惠手续费?
猜你喜欢

Go from introduction to actual combat - panic and recover (notes)

Codeforces Global Round 14

STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP

win11桌面出現“了解此圖片”如何删除

Go从入门到实战—— 多路选择和超时控制(笔记)

Go from entry to practice -- CSP concurrency mechanism (note)

Special training of guessing game

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

vmware虚拟机PE启动

AI 绘画极简教程
随机推荐
vmware虚拟机PE启动
VMware vSphere esxi 7.0 installation tutorial
Go从入门到实战——所有任务完成(笔记)
Go from introduction to actual combat - package (notes)
Scrum和看板的区别
excel读取文件内容方法
Quick excel export according to customized excel Title Template
ABC-Teleporter Setting-(思维+最短路)
Go從入門到實戰——接口(筆記)
[LeetCode]161. 相隔为 1 的编辑距离
数组作业题
100 important knowledge points that SQL must master: combining where clauses
SQL必需掌握的100个重要知识点:排序检索数据
Burp suite遇到的常见问题
Is it safe to open an account and buy stocks? Who knows
强制 20 天内开发 APP 后集体被裁,技术负责人怒批:祝“早日倒闭!”
Use the storcli tool to configure raid. Just collect this article
抖音的兴趣电商已经碰到流量天花板?
GBase 8a OLAP分析函数 cume_dist的使用样例
Go从入门到实战——错误机制(笔记)