博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode C++ 572. Subtree of Another Tree【Tree/DFS】简单
阅读量:2005 次
发布时间:2019-04-28

本文共 1308 字,大约阅读时间需要 4 分钟。

Given two non-empty binary trees s and t , check whether tree t has exactly the same structure and node values with a subtree of s . A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.

Example 1:

Given tree s :

3    / \   4   5  / \ 1   2

Given tree t:

4   / \ 1   2

Return true , because t has the same structure and node values with a subtree of s .

Example 2:

Given tree s :

3    / \   4   5  / \ 1   2    /   0

Given tree t :

4  / \ 1   2

Return false .

题意:判断 t 是不是 s 的某个子树。要求结构相同,对应结点的值也相同。


思路:双重DFS

相当于回顾了 LeetCode 100. 相同的树 这一题。我们先序DFS遍历 s 的所有结点,对以当前结点为根的每个子树,都和 t 进行树是否相同的判断。具体代码如下:

class Solution {
public: bool isSubtree(TreeNode* s, TreeNode* t) {
if (s == nullptr) return false; //s遍历完了,t给定为非空树,所以返回false return isSameTree(s, t) || isSubtree(s->left, t) || isSubtree(s->right, t); //短路运算符,有一个为真,返回真 } //LeetCode 100题 相同的树的那个函数 bool isSameTree(TreeNode *s, TreeNode *t) {
if (!s && !t) return true; //两子树相同 if (!s || !t) return false; //有一个不为空 if (s->val != t->val) return false; return isSameTree(s->left, t->left) && isSameTree(s->right, t->right); }};

效率如下:

执行用时:44 ms, 在所有 C++ 提交中击败了71.61% 的用户内存消耗:28.5 MB, 在所有 C++ 提交中击败了65.21% 的用户

转载地址:http://elotf.baihongyu.com/

你可能感兴趣的文章
odoo10学习笔记十六:定时任务
查看>>
commons-dbutils【不推荐】
查看>>
系统横向扩展与垂直扩展
查看>>
业务系统接入单点登录服务
查看>>
eos 源码资源限制两个对象
查看>>
SOCAT端口转发
查看>>
docker快速搭建HTTP代理
查看>>
docker解决时间不同步的问题
查看>>
jooq各种条件笔记
查看>>
jpa的entry审查Auditing
查看>>
mongdb查询笔记
查看>>
mapstruts的基本使用
查看>>
fabric智能合约(chaincode)升级版本
查看>>
fabric超级账本msp配置文件生产
查看>>
facebook区块链libra测试网体验
查看>>
拆箱与装箱
查看>>
Java反射
查看>>
Java面向对象三巨头
查看>>
前端学习 -- 内联框架iframe
查看>>
【bug】Could not find method compile() 解决
查看>>