Tree_Graph 判断T2是否为T1的子树 @CareerCup

【科学刷题】树的子结构与子树判断 文章目录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. 查 阅读详情

原文:

You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1

译文:

有两棵很大的二叉树:T1有上百万个结点,T2有上百个结点。写程序判断T2是否为T1的子树。


思路:

1) 因为中序前序遍历就可以决定一棵树,把两棵树的中序前序都写出来,如果两个遍历中T2都是T1的子串,可以确定T2是T1的子树。

当然这会遇到无法区分


的情况。因为

T1, in order: 3,3    T1, pre order 3,3

T2, in order: 3,3    T2, pre order 3,3

所以必须也算入null节点,所以

T1, in order: 0, 3, 0, 3, 0    T1, pre order 3, 3, 0, 0, 0

T2, in order: 0, 3, 0, 3, 0    T2, pre order 3, 0, 3, 0, 0

这种方法时间复杂度:O(n+m), 空间复杂度:O(n+m) , n,m分别为两个树的节点数。当海量数据时不适用!

2)递归!从根节点往下递归,判断子树是否存在其的左子树或右子树内。
时间复杂度:O(nm), 空间复杂度:O(log(n) + log(m))
但实际上,在真实的运行时,递归假如发现满足子树的条件就直接返回,而不会继续查找。因此递归法在实际中无论时间空间更优!

package Tree_Graph;

import CtCILibrary.AssortedMethods;
import CtCILibrary.TreeNode;

public class S4_8 {

	// 判断t2是否是t1的子树
	public static boolean isSubTree(TreeNode t1, TreeNode t2) {
		if(t2 == null) {			// 空树始终是另一个树的子树
			return true;
		}
		if(t1 == null) {		// 此时r2非空,非空树不可能是一个空树的子树
			return false;
		}
		if(t1.data == t2.data) {			// 找到两树匹配
			if(isSameTree(t1, t2)){
				return true;
			}
		}
		
		// 继续在r1的左子树和右子树里找匹配
		return isSubTree(t1.left, t2) || isSubTree(t1.right, t2);
	}
	
	// 判断两棵树是否相同
	public static boolean isSameTree(TreeNode t1, TreeNode t2) {
		if(t1==null && t2==null) {
			return true;
		}
		if(t1==null || t2==null) {
			return false;
		}
		
		if(t1.data != t2.data) {
			return false;
		}
		return isSameTree(t1.left, t2.left) && isSameTree(t1.right, t2.right);
	}
	
	public static void main(String[] args) {
		// t2 is a subtree of t1
		int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
		int[] array2 = {2, 4, 5, 8, 9, 10, 11};

		TreeNode t1 = AssortedMethods.createTreeFromArray(array1);
		TreeNode t2 = AssortedMethods.createTreeFromArray(array2);

		if (isSubTree(t1, t2))
			System.out.println("t2 is a subtree of t1");
		else
			System.out.println("t2 is not a subtree of t1");

		// t4 is not a subtree of t3
		int[] array3 = {1, 2, 3};
		TreeNode t3 = AssortedMethods.createTreeFromArray(array1);
		TreeNode t4 = AssortedMethods.createTreeFromArray(array3);

		if (isSubTree(t3, t4))
			System.out.println("t4 is a subtree of t3");
		else
			System.out.println("t4 is not a subtree of t3");
	}
}



 


告别卡顿!用U盘给你的MacBook Pro 2015+来一次macOS Monterey的‘大扫除’式安装 每次系统升级后,老款MacBook Pro用户最常抱怨的就是"怎么比之前更卡了?"——这不是错觉。系统迭代过程中积累的缓存文件、残留配置和隐形服务,就像房间角落堆积的灰尘,拖慢了整台机器的响应速度。而通过U盘进行的macOS Monterey全新安装,本质上是一次彻底的"数字大扫除":它不仅替换系统文件,还会重建所有索引、清理磁盘碎片,甚至能解决某些玄学般的卡顿问题。对于2015款及之后的MacBook Pro用户,这种安装方式能让老设备重获新生。 阅读详情

相关推荐

AUTOSAR开发实战:NvM模块如何解决汽车电子中的EEPROM与Flash存储难题?

本文深入探讨了AUTOSAR中的NvM模块如何有效解决汽车电子系统中EEPROM与Flash存储的难题。通过分层架构设计,NvM模块实现了硬件抽象与统一管理,支持数据一致性检查、错误恢复等高级功能,显著提升了存储可靠性和耐久性。文章结合实战案例,详细解析了NvM的核心机制及工程优化方案,为汽车电子开发者提供宝贵参考。

e3f4g5的博客 564

Two trees, T1 and T2, are isomorphic if T1 can be transformed into T2 by swapping left and right chi

Two trees, and , are isomorphic if can be transformed into by swapping left and right children of (some of the) nodes in . For instance, the two trees in Figure 1 are isomorphic because they are the same if the children of A, B, and G, but not the other

linjianchu的博客 852

Python实现支付宝转账接口

由于工作需要使用python开发一个自动转账接口,记录一下开发过程。 首先需要在蚂蚁金服上申请开通开发者账户,有了开发者账户就可以使用沙箱进行开发了。 在开发之前我们需要在沙箱应用中填写密钥,密钥的获取可以使用阿里提供的工具包自动生成。 前期准备工作完成了,接下来是编写代码部分。主要用到了python-alipay-sdk库,使用pip安装即可,如果安装的过程中遇到问题推荐使用Anaconda...

FanMLei的博客 8516

二叉树--2-树的子结构--子树匹配

题目    输入两颗二叉树A,B,判断B是不是A的子结构。(PS:我们约定空树不是任意一个树的子结构)。思路    要查找树A中是否存在和树B结构一样的子树,我们可以分为两步:            第一步在树A中找到和B的根结点的值一样的结点R,            第二步再判断树A中以R为根节点的子树是不是包含和树B一样的结构。    使用递归的方法即可。注意    这道题目不能利用先序遍历...

ax_hacker的博客 1709

门控时钟(clock gating)的DFT设计

在数字IC芯片中,时钟树的功耗占比可能高达30%,因此一般会采取门控时钟的方式来降低该部分的功耗。所谓门控时钟,就是在芯片实际工作过程中,有些信号或者功能并不需要一直开启,那么就可以在它们不用的时候将其时钟信号关闭。这样一来信号不再翻转,从而能够有效减少动态功耗。 目前门控时钟都采用集成门控时钟单元(ICG,integrated clock gating cell),其结构如下。由一个latch和一个与门(也有的是或门)组成,可以过滤掉EN信号中的毛刺。一般的工艺库中都会有专门的ICG以供调用。 插入IC

weixin_44746697的博客 3874

VTK学习(入门级教程,包括安装和使用)~持续更新中

说明:研究QT+VTK有段时间了,准备把学到的东西分享给大家,这篇博客以VS+QT+VTK为主进行展开学习的。

HXX904的博客 4756

每天一个算法之子树匹配

package ff; import java.util.Scanner; class BinaryTree{ int data; BinaryTree left; BinaryTree right; } public class isSubTree { static Scanner sc=new Scanner(System.in); public static

u012749168的博客 1463

保姆级教程:用北醒TFmini-i-CAN雷达给PixHawk飞控加装‘眼睛’,实现自动避障与定高

经过多次测试,前向雷达的最佳安装位置是机架前部下方5-10cm处,倾斜角度20-30度。电源方面,建议为CAN设备单独供电,避免电机启动时的电压骤降导致数据异常。北醒TFmini-i-CAN雷达与PixHawk飞控的组合,为DIY爱好者打开了低成本实现智能避障的大门。实际部署时,需确保整个CAN网络的波特率一致(TFmini-i默认为250kbps),每个设备具有唯一ID。雷达的安装角度也直接影响检测效果,建议通过3D打印支架将雷达向前下方倾斜15-30度。当使用多个雷达时,需为每个设备创建独立的参数组。

weixin_30892889的博客 337

树形地铁系统

题目 题目 思路 前两种是https://www.acwing.com/solution/content/4142/中读到的。 1 我们肯定是想要把两棵树的最小表示找出来,然后看看是否相同。 在这种情况下,我们期望是每个点在其子树内按最长链长度从大到小选择子节点进行DFS,但是如果相同呢?我们就要在链上干同样的事情,理论上我认为记忆性搜索应该可以到O(n2)O(n^2)O(n2),但我更认为我打不出这个代码。 2 上一种方法的优化,就是直接把子节点的最小表示求出来,然后子节点的最小表示再按字典序拼起来,然后

蒟蒻QMQ 200

16、天文时间序列分类:基于人工神经网络的研究

本研究探讨了基于人工神经网络的天文时间序列分类方法,重点比较了MLP、LSTM和CNN等模型在BRITE和开普勒K2数据集上的表现。研究发现LSTM不适用于此类数据,而结合特征提取与PSO超参数优化的多层感知器(MLP)在开普勒K2数据上实现了98.55%的二分类准确率。通过精细的数据预处理和高置信度样本选择,显著提升了分类性能。研究成果为恒星变异性识别提供了高效工具,并对天文学与机器学习交叉领域具有重要参考价值。

pz8901234的博客 113

基于Simulink与MATLAB的七轴OpenArm机械臂逆运动学仿真与轨迹规划完整指南

本文详细介绍了七自由度OpenArm机械臂在MATLAB/Simulink环境下的运动学仿真与轨迹规划实现方法。首先建立了机械臂的DH参数模型,验证了正运动学计算;随后提出了两种逆运动学求解算法(数值迭代法和臂型角参数化解析法)的MATLAB实现方案;最后在Simulink中搭建了完整的轨迹规划与控制系统。研究解决了七自由度冗余机械臂特有的多解性、奇异性和关节限位约束等核心问题,为OpenArm机械臂的运动控制提供了完整的技术方案和可运行代码实现。

AI的内部世界的博客 681

树同构简单Hash法

DESCRIPTION: 给出两棵节点数相同的树,求其是否同构,还要输出可行解(节点的匹配关系)带spj。 input 16(n个节点) 12 4 4 13 13 5 13 14 4 8 8 3 8 6 3 15 12 10 15 1 4 9 4 2 2 7 12 16 1 11 7 6 6 2 2 10 2 11 6 9 9 14 9 8

雾腾腾 824

基于Simulink的光伏-储能-柴油机混合微网仿真

摘要:本文基于Simulink平台构建光伏-储能-柴油机混合微网仿真模型,实现可再生能源与备用电源的协同控制。通过光伏优先、储能调节、柴油机兜底的规则控制策略,在24小时仿真中验证了系统在晴天、阴天和夜间三种典型工况下的运行性能。模型采用PVArray模块模拟光伏发电,Simscape电气库构建储能系统,自定义MATLAB函数实现柴油机启停逻辑和能量管理。仿真结果显示系统功率平衡误差<5%,储能SOC维持在20%-80%,柴油机日均运行时间<4小时,满足设计指标。文章详细说明了建模步骤、参数设置

xiaoheshang_123的博客 68

4-11 Isomorphic(判断两树同构)

Two trees, T1 and T2, are isomorphic if T1 can be transformed into T2 by swapping left and right children of (some of the) nodes in T1. For instance, the two trees in Figure 1 are isomorphic because they are the same if the children of A, B, and G, but not

wyx_601的博客 1470

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

lintcode子树

1.描述; 有两个不同大小的二进制树: T1 有上百万的节点; T2 有好几百的节点。请设计一种算法,判定 T2 是否为 T1的子树。  注意事项 若 T1 中存在从节点 n 开始的子树与 T2 相同,我们称 T2 是 T1 的子树。也就是说,如果在 T1 节点 n 处将树砍断,砍断的部分将与 T2 完全相同。 您在真实的面试中是否遇到过这个题? 

import_torch_as_tf 339

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

572.subtree-of-another-tree

给你两棵二叉树 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],

qq_26000415的博客 337

深度学习工具包 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")

[BZOJ3197][Sdoi2013]assassin(树形DP+树同构+二分图最优匹配)

关于树同构,有一个神奇的性质: 一棵树的重心只有 111 个或 222 个,如果有 222 个(记为 uuu 和 vvv),那么一定有边 (u,v)(u,v)(u,v) ,而此时可以断开边 (u,v)(u,v)(u,v) ,新建一个节点,分别向 uuu 和 vvv 建边,这样新建的节点就是重心。上面所说的性质是:如果有两棵树,强制以重心为根,那么这两棵树同构当且仅当形成的两棵有根树同构。 而两...

女装的你,如此好看! 394

【树-简单】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,

... 138

leetcode: 另一个树的子树(暴力匹配,KMP,树hash)

给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。 一刷: class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: def help(s: TreeNo...

qqMiSa的博客 299

(245)LintCode 之判定 T2 是否为 T1的子树

题目:有两个不同大小的二叉树:T1有上百万的节点;T2有好几百的节点。请设计一种算法,判定T2是否为T1的子树。

qq_36464448的博客 517

树T1交换其(某些)左右节点的左右儿子变换成树T2,则是同构。给出一个多项式时间算法以决定是否两棵树同构

数据结构与算法分析——c语言描述 练习4.42a 答案 很惭愧,不会计算复杂度。大神看到了请指教。 int IsIsomorphic(SearchTree t1, SearchTree t2) { if (t1&&t2) { if (t1->element != t2->element) return 0; return (isomorphic(t1->left

wwj_bupt 3091

判断树T2是否为T1的子树

题目 你由两颗非常大的二叉树:T1,有几百万个节点;T2有几百个节点。 设计一个算法,判断T2是否为T1的子树。 如果T1有一个节点n,其子树与T2一模一样,则T2为T1的子树。也就是说,从节点n 处把树砍断,得到的树与T2完全相同。 分析 方法一:在规模较小且较简单的问题中,我们可以创建一个字符串,表示中序和前序遍历结果。若T2的前序遍历是T1前序遍历的子串,并且

指尖飞舞 1973

020给定两个二叉树T1,T2判断T1是否是T2的子树(keep it up)

给定两个二叉树T1,T2判断T1是否是T2的子树 首先在T2中查找T1的根节点,如果找不到, 则T1不是T2的子树,如果能找到,我们可以 遍历T1,检查T1的每个结点是否对应的存在T2 中。 代码: struct TreeNode { int data; TreeNode* leftChild; TreeNode* rightChild; }; bool isExited(co

yanziguilai的专栏 2193

判定 T2 是否为 T1的子树

有两个不同大小的二叉树:T1有上百万的节点;T2有好几百的节点,判定T2是否为T1的子树。 思路:假设T1是母树,T2是子树。遍历母树,找到T1节点与T2的根节点相同的点,如果找到的话。则继续遍历T1与T2,判断是否具有相同的结构,如果有相同的结构,则T2是T1的子树,返回tr...

229

判断t2树是否为t1树的子树(Java)

判断t2树是否为t1树的子树 (牛客网—牛客题霸算法篇—NC98) 题目描述 给定彼此独立的两棵二叉树,树上的节点值两两不同,判断 t1 树是否有与 t2 树完全相同的子树。 思路 Java实现 递归 要判断t2是否为t1的子树,那么就先在t1中找到t2的根节点,然后再进行遍历。 判断从当前节点的左右子树相不相同,如果一旦出现不同,那么立即返回false。 如果t2遍历完节点,t1也遍历完节点,则证明t2为t1的子树。 如果t1先遍历完节点,t2还没遍历完节点,那么则证明t2不是t1的子树。 在isCont

ln01010的博客 436

二叉树问题---判断t1树是否包含t2树全部的拓扑结构

#判断t1树是否包含t2树全部的拓扑结构 def isContain(t1, t2): def check(t1, t2): if not t2: return True if not t1 or t1.val != t2.val: return False return check(t1.lef

冰殇的博客 885
上一篇: Tree_Graph LCA(Lowest Common Ancestor) 最低公共节点 (BST或者一般树) @CareerCup
下一篇: Tree_Graph 打印所有和为定值的路径 @CareerCup
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值