当前位置:网站首页>[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);
}
边栏推荐
- Little known MySQL import data
- Go从入门到实战——行为的定义和实现(笔记)
- White whoring red team goby & POC, how do you call white whoring?
- How to delete "know this picture" on win11 desktop
- Go from introduction to actual combat -- channel closing and broadcasting (notes)
- Go from introduction to practice - Interface (notes)
- 专题教程——选队长游戏
- Method of reading file contents by Excel
- Go从入门到实战——Context与任务取消(笔记)
- 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!"
猜你喜欢
随机推荐
win11桌面出現“了解此圖片”如何删除
excel读取文件内容方法
Go從入門到實戰——接口(筆記)
STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP
100 important knowledge points that SQL must master: filtering data
A set of system to reduce 10 times the traffic pressure in crowded areas
强制 20 天内开发 APP 后集体被裁,技术负责人怒批:祝“早日倒闭!”
快递e栈——数组篇小型项目
Bit.Store:熊市漫漫,稳定Staking产品或成主旋律
GBase 8a OLAP函数group by grouping sets的使用样例
Process control task
.NET学习笔记(五)----Lambda、Linq、匿名类(var)、扩展方法
GBase 8a的create database 会被查询耗时很长怀疑卡住的现象分析
Full record of 2022 open source moment at Huawei partners and Developers Conference
Galaxy Kirin system LAN file sharing tutorial
Method of reading file contents by Excel
IO stream code
TypeScript学习
Go from entry to practice - dependency management (notes)
Bit. Store: long bear market, stable stacking products may become the main theme