树的子结构

【科学刷题】树的子结构与子树判断 文章目录1. 判断【树B】是否是【树A】的【子结构】/【子树】1.1 概念阐述1.2 完全匹配的情况1.3 部分匹配的情况2. 查找所有重复子树 1. 判断【树B】是否是【树A】的【子结构】/【子树】 1.1 概念阐述 首先阐述一个概念:子结构匹配与子树匹配 匹配: 完全匹配就是A的子结构与B完全匹配 部分匹配: 部分匹配就是A的子结构与B部分匹配,A的子结构允许有与B不匹配的其他结构 如何判断是【完全匹配】还是【部分匹配】呢?我们需要仔细读题: 1.2 完全匹配的情况 1.3 部分匹配的情况 2. 查 阅读详情

题目描述

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

源代码:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        boolean res=false;
        if(root1!=null&&root2!=null){
                 res= tree1Hastree2(root1,root2);//先看两个树的根节点是否匹配
        if(res==false){////如果两个树的根节点不匹配,再看第二个树是否和左子树匹配
            res = HasSubtree(root1.left,root2);
        }
        if(res==false){
            res = HasSubtree(root1.right,root2);//如果第二个树和左子树不匹配,则比较第二个树是否和右子树匹配
        }
        }
        return res;
    }
    
    public boolean tree1Hastree2(TreeNode root1,TreeNode root2) {
        if(root2==null){//如果树2为空,则肯定匹配
            return true;
        }
        if(root1==null&&root2!=null){//如果树1为空,树2不为空,则不匹配
            return false;
        }
        if(root1.val!= root2.val){
            return false;
        }
        return  tree1Hastree2(root1.left,root2.left)&&tree1Hastree2(root1.right,root2.right);//如果两棵树的根节点匹配,则再接着比较两棵树的左子树、两棵树的右子树分别是否匹配
    }
}

 

Deepseek+Word插件:一键搞定论文翻译与润色的学术写作新革命 本文介绍了Deepseek Word插件如何革新学术写作流程,实现论文翻译与润色的一键操作。该插件深度集成于Word环境,能智能完成中英互译、语法修正、术语统一及逻辑优化,显著提升写作效率与文本质量,是研究者的高效AI助手。 阅读详情

相关推荐

自动驾驶仿真(二)—— 基于PreScan与Simulink的联合仿真

自动驾驶仿真软件介绍二—— PreScan与Simulink联合仿真1. Prescan仿真软件2. Prescan与Simulink联合仿真2. 1 Prescan和matlab软件安装2. 2 联合仿真配置3. 联合仿真实例3.1 一辆不按法规行驶的小车3.2 另一辆的正常行驶的小车3.3 视觉辅助摄像机3.4 传感器检测4. 系列学习视频教程5. 参考学习的书目教材 上一篇博文简单介绍了Carsim与Simulink联合仿真,接着这篇就再继续简单介绍另一款自动驾驶仿真软件Prescan,并且简单做个P

zhudj08的博客 1万+

《剑指offer》-- 树的子结构、二叉树的镜像、二叉树的深度、平衡二叉树

一、 树的子结构: 1、题目: 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构。 2、解题思路: 这个题比较简单,利用递归的方式就可以判断B是不是A树的子结构。 3、实现代码: public boolean HasSubtree(TreeNode root1,TreeNode root2) { //当tree1和tree2都不为空...

张维鹏的博客 516

Hi3516CV610开发板实战:从零搭建智能视觉监控系统

本文详细介绍了从零开始基于Hi3516CV610开发板搭建智能视觉监控系统的完整实战流程。涵盖硬件连接、系统配置、摄像头集成、网络设置、固件烧录到视频处理与智能分析功能开发,提供了丰富的实践经验和调试技巧,帮助开发者快速掌握嵌入式视觉系统开发。

vvv99的博客 565

【整理自用】二叉树的子树、子结构

二叉树的子树和子结构 子树的意思是只要包含了一个结点,就得包含这个结点下的所有节点. 子结构的意思是包含了一个结点,可以只取左子树或者右子树,或者都不取。 简单而言,与子树不同的是,子结构可以是A树的任意一部分。 这里以一颗7节点,高度为3的满二叉树为例,说明子树和子结构的差别: 图1 1.图1的子树示意图 对于图1而言,子树意味着图2,图3等情况。根据定义非...

wushuomin的博客 1万+

Pdu Router(PduR)模块

1. PduR路由基本功能 2. PduR总线网关功能 3. PduR缓存机制 4. 总结

weixin_43759043的博客 3850

华为流程L1-L6业务流程深度细化到可执行【附全文阅读】

该文档主要介绍了华为业务流程的深度细化及相关内容,包括流程框架、建模方法、流程模块描述、流程图建模等,旨在帮助企业构建有效的流程体系,实现战略目标。

cdfunlove的博客 4007

17.树的子结构

树的子结构 题目链接 题目描述 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) 子树与子结构的概念 子树:指包含树的某个结点下的所有结点的树结构。一个n个结点的二叉树有n棵子树。[CADB,A,DB,B,H,EHGM,GM…]等都是该二叉树的子树。 子结构:指包含树的某个结点,可包含左子树或者右子树,或者都左右子树包含的树结构。这样只要与树某一个结点有...

Stay Hungry, Stay Foolish. 522

【人工智能】RAG如何根据实际需求选择和进行文档解析(如 PDF、Word、TXT、网页等)?

文档解析的核心在于根据解析目标、文档类型和处理量选择合适工具。PDF、Word、TXT和网页各有特性:PDF需区分可编辑与扫描版,Word需处理结构化内容,TXT简单但需注意编码,网页需应对动态内容。解析场景包括提取纯文本、结构化数据、保留格式和批量处理。非技术用户可借助工具如Adobe Acrobat、WPS和在线OCR,技术用户可通过编程实现自动化。通用流程为:明确目标、分析文档属性、选择工具并测试优化。核心是“工具适配需求”,无需追求万能方案。

奶爸的编程之路,也就一周冷个三天 509

26. 树的子结构

文章目录剑指offer 26 树的子结构解题思路:Java代码扩展题:LeetCode572 另一个树的子树572. 另一个树的子树解题思路Java代码 剑指offer 26 树的子结构 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 例如: 给定的树A: 3 / \ 4 5 / \ 1 2 给定的树 B: 4 / 1 返回 true,因为 B 与 A 的一个子

YouMing_Li的博客 541

ITKMontage---ITK自动拼接模块

本文分享ITK中Remote中的ITKMontage拼接模块,希望对各位小伙伴有所帮助!1. ITKMontage介绍在医疗图像处理过程中,图像拼接有很多用处,比如DR图像的拼接。ITKMontage可以快速稳定的处理数据量较大的拼接图像。强度不均匀性校正配准全局优化融合2. ITKMontage安装ITKMontageITKMontage可脱离ITK进行单独安装,也可在ITK安装时作为模块进行安装。单独安装ITK模块安装在ITK编译时,选择ITKMontage模块。

qq_40041064的博客 450

【Bluetooth|蓝牙开发】二、蓝牙开发入门

蓝牙,是一种利用低功率无线电,支持设备短距离通信的无线电技术,能在包括移动电话、PDA、无线耳机、笔记本电脑、相关外设等众多设备之间进行无线信息交换,蓝牙工作在全球通用的2.4GHz ISM(即工业、科学、医学)频段,使用IEEE802.11协议。

Donge's Blog 1万+

树的子结构和树的子树的区别

另一个树的子树 剑指 Offer 26. 树的子结构 以上题来源:力扣 这两道题的区别: 首先我们要区分这两者的区别,那么就好理解了 树的子结构: B是A的子结构, 即 A中有出现和B相同的结构和节点值。(约定空树不是任意一个树的子结构) 例如: 给定的树 A: 3 / \ 4 5 / 1 2 给定的树 B: 4 / 1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。 另一个树的子树: 示例 1: 给定的树 s: 3 / \ 4 5 / 1 2 给定的树 t

m0_48810566的博客 493

L型探测器几何畸变矫正

定位像素空间位置 -> 计算水平面投影点 -> 统一物理分辨率 -> 重采样生成新图。

如果想成为中心,那么就到中心去吧。 243

树的子结构&&二叉树的镜像

树的子结构 解题思路 1.判断root1和root2的根结点是否相同,相同比较root1和root2的左右子树是否相同 2.root1与root2的根结点不匹配,递归判断root1的左右子树判断 代码 /** * 剑指offer一刷:树的子结构 * * @author User * @create 2019-05-18-19:54 */ public class jzo17 { ...

weixin_41676282的博客 1509

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

[剑指Offer]树的子结构(Java)

剑指Offer题目 树的子结构 -- newcoder 剑指Offer 17 题目描述 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) 思路 * 思路1: * 1、层次遍历root1, 找到与root2相同的节点(此步骤非递归) * 2、找到后判断以此节点为根节点,是否能在root1中找到与root2相同的树结构(此处判断用递归查找) * ...

聚沙成塔 327

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

剑指offer-树的子结构

11.树的子结构 题目内容: 代码及思路: 如果有更好的写法,非常愿意和大家一起交流 #include<iostream> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; }; class solution { public: void build...

larklili的博客 439

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

树的子结构(中等难度,好题目)

目录题目概述(中等难度)思路与代码思路展现代码示例总结 题目概述(中等难度) 题目链接: 点我进入leetcode 思路与代码 思路展现 这道题目首先跟之前的一道题目非常的类似,但其实有所不同,在此先贴上链接: 另一课树的子树 先来说一点:树的子结构跟子树是完全两个不同的概念,准确来说树的子结构更像是包含了子树的概念,例如对与[1,2,3,4,5]这棵树而言,[2,4,5]是他的子树,但是2不能作为它的子树,但是可以作为子结构. 先来看代码,我们挨个进行解析 代码示例 class Solution {

想要成为大佬的彪彪 654

关于剑指Offer 树的子结构的讨论

第二次看到这个题还是不会....参考了这道题牛客网排名第一的答案,在理解的过程中,我认为这个答案有问题,如果是我理解错了,欢迎讨论指正。 关于树的子结构的定义,网上也没有很明确的说法,个人理解就是,只要小树是大树结构中的一部分就行。(子结构与子树一定要区分开来,最后会介绍两者区别。) 首先,根据剑指offer书上的测试用例,测试了牛客排名第一的答案左边为大树,右边为小树,显然结果是true。 ...

qinian_ztc的博客 4447

周三第三题   树的子结构

AcWing打卡活动 《剑指Offer》打卡活动 周三第三题树的子结构 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) {...

一步一阶梯 226

剑指Offer(Python多种思路实现):树的子结构

剑指Offer(Python多种思路实现):树的子结构 面试26题: 题目:树的子结构 题:输入两棵二叉树A和B,判断B是不是A的子结构。 解题思路一:递归,注意空指针的情况。 class Solution: def HasSubtree(self, pRoot1, pRoot2): # write code here res=False ...

weixin_44151089的博客 1181

剑指 Offer 26. 树的子结构

链接:剑指 Offer 26. 树的子结构 先判断B是否为A当前的子结构,如果不是,递归判断B是否为A左子树的子结构,是否为A右子树的子结构。注意判断两个结构是否相同的时候应该单独用一个函数实现 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.rig.

breeze_blows的博客 271

树的子结构&树的子树

前者是剑指offer上的题目,后者属于力扣。主要差别就在于对于以下例子,前者返回True,后者返回False。 3 4 / \ / \ 4 5 ...

qq_34597865的博客 366
上一篇: 合并两个排序的链表
下一篇: 二叉树的镜像
It_BeeCoder
博客等级 码龄10年 967粉丝 238原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值