PAT甲级 - 1099 Build A Binary Search Tree (30 分) 重建二叉搜索树

数据结构英文习题解析-第五章 二叉搜索树Binary Search Tree A 这道题目我看了好久,可以通过根节点左右子树大小判断mid取大还是取小,比如A选项这张图左子树5个节点右子树4个节点,那mid是(left+right)/2+1(取大);前言:最近快到FDS考试了,po重刷了一下学校的题目,自己整理了一些解析orz 因为po在自己找解析和学习的过程中非常痛苦,所以在此共享一下我的题目和自己写的解题思路,欢迎各位指出错误~全章节预计会陆续更新,可在专栏查看~4和6可能不是同一个parent的两个child,可能4是rchild,6是lchild。1<3<5<4<2; 阅读详情

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

Given the structure of a binary tree and a sequence of distinct integer keys, there is only one way to fill these keys into the tree so that the resulting tree satisfies the definition of a BST. You are supposed to output the level order traversal sequence of that tree. The sample is illustrated by Figure 1 and 2.

figBST.jpg

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤100) which is the total number of nodes in the tree. The next N lines each contains the left and the right children of a node in the format left_index right_index, provided that the nodes are numbered from 0 to N−1, and 0 is always the root. If one child is missing, then −1 will represent the NULL child pointer. Finally N distinct integer keys are given in the last line.

Output Specification:

For each test case, print in one line the level order traversal sequence of that tree. All the numbers must be separated by a space, with no extra space at the end of the line.

Sample Input:

9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42

Sample Output:

58 25 82 11 38 67 45 73 42

和A1064很像,中序重建树即可。

//给出树的结构,给出要添加的元素; 按照树的某种遍历是有序的,将元素添加进去
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 150;
struct Node {
	int data;
	int left, right;
}node[maxn];
int origin[maxn];
int n;
int index = 0;

void InOrder(int root) {
	if (root == -1) //到达叶结点
		return;
	InOrder(node[root].left);
	node[root].data = origin[index++];
	InOrder(node[root].right);
}

int num = 0;
void LevelOrder(int root) {
	queue<int> q;
	q.push(root);
	while (!q.empty()) {
		int top = q.front();
		printf("%d", node[top]);
		num++;
		if (num < n)
			printf(" ");
		q.pop();
		if (node[top].left != -1)
			q.push(node[top].left);
		if (node[top].right != -1)
			q.push(node[top].right);
	}
}

int main() {
	scanf("%d", &n);
	int lchild, rchild;
	for (int i = 0; i < n; i++) {
		scanf("%d%d", &lchild, &rchild);
		node[i].left = lchild;
		node[i].right = rchild;
	}
	for (int i = 0; i < n; i++) {
		scanf("%d", &origin[i]);
	}
	sort(origin, origin + n);
	InOrder(0);
	LevelOrder(0);

	return 0;
}

 

PAT-A1099 Build A Binary Search Tree 题目内容及题解 A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right su... 阅读详情

相关推荐

PAT-甲级-1099 Build A Binary Search Tree (30 分)

1099Build A Binary Search Tree(30分) A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys...

valcanoshan的博客 330

数据结构5 Binary Search Tree

Binary Search Tree定义 1.是二叉树 2.左孩子<根<右孩子 3.左右子树都是BST 操作 1.寻找元素X 递归法: Position Find( ElementType X, SearchTree T ) { if ( T == NULL ) return NULL; /* not found in an empty tree */ if ( X < T->Element ) /* if smaller

HGGshiwo的博客 8934

GNSS-RTK/INS紧组合里,那个‘杆臂改正’到底怎么算?一个公式讲清INS与天线位置的关系

本文深入解析GNSS-RTK/INS紧组合导航系统中的杆臂改正(Lever Arm Correction)原理与实现方法。详细介绍了杆臂效应的物理本质、数学建模及误差扰动分析,揭示了IMU与GNSS天线位置关系的核心公式,并提供了工程实现中的常见误区与验证方法。通过Python代码示例和紧组合量测模型处理流程,帮助开发者准确理解并应用这一关键技术。

weixin_33137081的博客 357

1099 Build A Binary Search Tree(树的遍历)

1099 Build A Binary Search Tree (30 分) A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node

adoge_的博客 549

【机器学习】实验2,基于回归分析的大学综合得分预测(完整代码实现+分析)

大学排名是一个非常重要同时也极富挑战性与争议性的问题,一所大学的综合实力涉及科研、师资、学生等方方面面。目前全球有上百家评估机构会评估大学的综合得分进行排序,而这些机构的打分也往往并不一致。在这些评分机构中,世界大学排名中心(Center for World University Rankings,缩写CWUR)以评估教育质量、校友就业、研究成果和引用,而非依赖于调查和大学所提交的数据著称,是非常有影响力的一个。

高丽大学人工智能硕士在读|专注大模型、RAG、OCR与AI工程实践 1979

激光可燃气体传感器:核心技术环节分析

激光可燃气体传感器核心技术涵盖七个维度:1)TDLAS光谱吸收与调制技术(检测下限ppm级);2)DFB激光器与双闭环温控系统(波长稳定性±0.0036nm);3)微弱信号处理技术(信噪比提升60dB);4)环境补偿算法(温压补偿误差<±1%);5)本质安全防爆设计(ExiaIICT4Ga等级);6)智能边缘计算(STM32L476芯片);7)多重性能验证(响应时间<1秒)。通过微型化、多气体检测等创新,该技术已在工业安全等领域替代传统方案,实现高精度检测。(149字)

上市公司前技术负责人,20 年软硬件深耕 + 百人研发团队管理经验,名校理工科背景加持。从技术攻坚到团队掌舵,沉淀海量项目实战与管理心得,专注分享软硬件干货、疑难问题解决方案,既是靠谱知识传播者,也盼链接优质项目共成长。 1047

PAT.A1099 Build A Binary Search Tree

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right su...

克拉拉的博客 385

SuperPoint+SuperGlue在HLoc中的实战效果对比:5大公开数据集测试报告

本文在HLoc框架下,对传统SIFT与深度学习组合SuperPoint+SuperGlue在五大公开数据集上的视觉定位效果进行了实战对比测试。报告详细分析了两种方案在Aachen Day-Night、RobotCar Seasons等不同光照、季节及场景下的表现,揭示了SuperPoint+SuperGlue在应对剧烈光照变化和长期外观变化时的显著优势,并提供了基于HLoc模块化设计的选型与配置策略。

weixin_29093169的博客 425

1099. Build A Binary Search Tree (30)-PAT甲级真题

1099. Build A Binary Search Tree (30) A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with key

柳婼 の blog 2880

手把手教你用TUSB2E22中继器实现eUSB2与USB 2.0互转(附实测数据对比)

本文详细介绍了如何利用TUSB2E22中继器实现eUSB2与USB 2.0的高效互转,包括技术背景、硬件设计要点、信号完整性测试方法及故障排查策略。通过实测数据对比,展示了TUSB2E22在信号延迟、功耗和眼图性能上的显著优势,为工程师提供了实用的工程方案。

weixin_29199873的博客 284

【RTD】AD7793驱动程序

AD7793完整驱动程序,支持两线、三线、四线RTD。

只要思想不滑坡,想法总比问题多。 6178

1099 Build A Binary Search Tree——PAT甲级

思路:首先根据给出的结点建立二叉树本身,之后按照给出的数字排序后以中序遍历的方式建立二叉搜索树。build函数是建树,built函数是将二叉搜索树数据读入已有的树。

flyidj的博客 1131

Apollo Planning决策规划算法代码详细解析 (2):Scenario执行

上一章节讲Scenario的决策逻辑,当确认当前Scenario后,本章节继续深入讲解在代码中,Scenario的执行过程。Scenario的Process()函数根据配置文件顺序执行stage,并判断目前处于哪个stage。当确认好stage后调用该stage对应的Process()函数,来进行具体的规划任务。 码字不易,喜欢的朋友们麻烦点个关注与赞。 在本文你将学到下面这些内容: Scenario的Process()函数的作用于调用方式; Scenario对象的初始化方法; 如何给每个Scen

自动驾驶Player的博客 5609

PAT甲级 1099 Build A Binary Search Tree (30 分)

\quad本题意在告诉你每个节点的左右孩子信息,需要你把树建出来,接着利用BST中序遍历值是有序的这一特性重新给每个节点赋值。最后再来个BFS对树进行层次遍历输出即可。 #include <bits/stdc++.h> using namespace std; int n; struct TreeNode { int val; int left, right; }treeNode...

qq_40438165的博客 1668

硬件工程师入门基础知识(一)基础元器件认识(二)

我们的电路输入一般是只有两种状态,0V 或者是其它的高电平(1.8V,3.3V,5V 等),截止状态一般不用怎么考虑,因为如果让三极管的 Vbe=0,自然就截止了,重要的是饱和状态如何保证。也就是说只要 Rb

小幽余生不加糖 1万+

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

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

PAT 甲级 1099  Build A Binary Search Tree

1099 Build A Binary Search Tree (30 point(s)) A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes wi...

漫浸天空的雨色的备忘录~ 973

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

【PAT甲级 - C++题解】1099 Build A Binary Search Tree

📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!

Newin2020的博客 811

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

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

pat甲级1099 build a Binary Search Tree

1099 Build A Binary Search Tree (30 分) A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys...

qq_41698081的博客 235

1099 Build A Binary Search Tree (30point(s)) - C语言 PAT 甲级

* 利用数组存储二叉搜索树 * 因为是二叉搜索树,节点的值序列排序后即为此树的中序遍历 * 中序遍历的过程中将节点值依次插入节点 * 再层序遍历一遍输出

有三只土豆 859

PAT甲级1099 Build A Binary Search Tree

本题考查 二叉搜索树 思路 给定二叉搜索树结构,给定二叉搜索树中所有结点键值,将这些键值插入,并输出层序遍历结果。 重点就是根据二叉搜索树结构插入键值,根据二叉搜索树左子树元素小于根结点,右子树元素大于根结点,可以确定假设左子树有L个结点,右子树有R个结点,则根结点就是已经排好序的候选键值中的第L+1个。得到以上结论,接下来的重点就是计算一个结点左右子树的结点数,可以使用递归的方法计算子树结点数,...

R.I.P Kobe Bryant 187

PAT甲级 -- 1099 Build A Binary Search Tree (30 分)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right su...

猪の成长日记 245

PAT甲级 1099 Build A Binary Search Tree (30分) DFS(中序)/C++

1099 Build A Binary Search Tree (30分) 题目大意:给定一棵结构已构建好的树,给定一串序列,要求按照二叉搜索树的规则将序列中的数字填入树框架中,再按层次遍历。 首先要明确:把中序遍历的结果push_back到数组v1里面,直接输出就是中序,排序输出就是层序(排序方式,层数小的排前面,相同层数时,index大的排前面 先将序列从小到大排序,得到中序序列;再中序遍历给定的树(框架),同时记录所在层次,并把对应层次的结点记录在vector中。 #include<iostre

qq_43955154的博客 205

pat甲级 树A1099 Build A Binary Search Tree (30分) 构建二叉搜索树

1099 Build A Binary Search Tree (30分) A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node c

weixin_42358356的博客 167

【PAT甲级】1099 Build A Binary Search Tree

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right...

haohulala的博客 235

PAT甲级——1099 Build A Binary Search Tree (二叉搜索数)

1099Build A Binary Search Tree(30分) A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys...

小熊猫的博客 436

1099 Build A Binary Search Tree (30 分) PAT甲级真题

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right su...

_Gray 381
上一篇: PAT - 1064 Complete Binary Search Tree (30 分) 完全二叉树和二叉搜索树
下一篇: PAT甲级1066 Root of AVL Tree (25 分)
DedicateToAI
博客等级 码龄9年 6粉丝 90原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值