PAT - A1043 Is It a Binary Search Tree (25 分)

Project 2: Counting Leaves A family hierarchy等级 is usually presented by a pedigree tree系谱树. Your job is to count those family members who have no child. 立即下载

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.

If we swap the left and right subtrees of every node, then the resulting tree is called the Mirror Image of a BST.

Now given a sequence of integer keys, you are supposed to tell if it is the preorder traversal sequence of a BST or the mirror image of a BST.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first print in a line YES if the sequence is the preorder traversal sequence of a BST or the mirror image of a BST, or NO if not. Then if the answer is YES, print in the next line the postorder traversal sequence of that tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input 1:

7
8 6 5 7 10 8 11

Sample Output 1:

YES
5 7 6 8 11 10 8

Sample Input 2:

7
8 10 11 8 6 7 5

Sample Output 2:

YES
11 8 10 7 5 6 8

Sample Input 3:

7
8 6 8 5 10 9 11

Sample Output 3:

NO

作者: CHEN, Yue

单位: 浙江大学

时间限制: 400 ms

内存限制: 64 MB

这道题对自己来说还是非常艰难,最后竟然写了将近100行,也写了很久。

  1. 根据元素的性质(大于等于还是小于根节点)来判断是1.BST 2.Mirror BST,同时划分出左子树。
  2. 在右子树中进行遍历,查看是否是BST。
  3. 递归check左子树和右子树。
#include<cstdio>
const int maxn = 1010;
int array[maxn] = { 0 };
int flag; //if flag = 1, BST ; flag = 0, mirror
bool result = true;
int cnt = 0;
struct node {
	int left, right;
}tree[maxn];


int check(int begin, int end) {
	int root = begin;
	if (begin == end)
		return begin;
	if (begin > end)
		return -1;
	if (flag == 1) {
		int i, j;
		//[begin + 1, i - 1]是左子树,[i,end]是右子树
		for (i = begin + 1; i <= end && array[i] < array[begin]; i++);
		for (j = i; j <= end; j++) {
			if (array[j] < array[begin]) {
				result = false;
				return -1;
			}

		}
		tree[root].left = check(begin + 1, i - 1);
		tree[root].right = check(i, end);
	}
	else if (flag == 0) {
		int i, j;
		//[begin+1, i - 1]是左子树,[i,end]是右子树
		for (i = begin + 1; i <= end && array[i] >= array[begin]; i++);
		for (j = i; j <= end; j++) {
			if (array[j] >= array[begin]) {
				result = false;
				return -1;
			}

		}
		tree[root].left = check(begin + 1, i - 1);
		tree[root].right = check(i, end);
	}
	return root;
}

void output(int root){
	if(tree[root].left != -1)
		output(tree[root].left);
	if (tree[root].right != -1)
		output(tree[root].right);
	if (cnt == 0)
	{
		printf("%d", array[root]);
	}
	else {
		printf(" %d", array[root]);
	}
	cnt++;
}

int main() {
	int N;
	scanf("%d", &N);
	for (int i = 0; i < N; i++) {
		scanf("%d", &array[i]);
		tree[i].left = -1;
		tree[i].right = -1;
	}
	if (array[1] < array[0])
		flag = 1;
	else
		flag = 0;
	int root = check(0, N - 1);
	if (result)
	{
		printf("YES\n");
		output(root);
	}
	else
		printf("NO\n");

	return 0;
}

看了《算法笔记》的标准答案,有种醍醐灌顶的感觉。

其实按照标准来解就好了,直接把先序序列插入BST,然后按两种方式输出先序序列进行比较,就可以判断出树是BST 还是Mirror BST,如果与两个序列都不相等,就直接输出No,最后在输出后序序列。

思路清晰,以不变应万变。

12.1:

再看这道题,依然要依靠标准答案。

教训:

不要被题意签着鼻子走,既然是BST,那么直接建一个BST就好了啊(一定是unique的) 

想清楚实现的逻辑,代码再长,也是很简单的

#include<cstdio>
#include<vector>
using namespace std;

vector<int> origin, pre, pre_mirror, post;

//vector<int> post;

const int maxn = 1050;
struct node {
	int data;
	node* left;
	node* right;
};

void insert(node*& root, int data) {
	if (root == NULL) {
		root = new node;
		root->data = data;
		root->left = root->right = NULL;
		return;
	}
	if (data < root->data) insert(root->left, data);
	else insert(root->right, data);
}

void PreOrder(node* root) {
	if (root == NULL)
		return;
	pre.push_back(root->data);
	PreOrder(root->left);
	PreOrder(root->right);
}

void PreOrderMirror(node* root) {
	if (root == NULL)
		return;
	pre_mirror.push_back(root->data);
	PreOrderMirror(root->right);
	PreOrderMirror(root->left);
}

void PostOrder(node* root) {
	if (root == NULL)
		return;
	PostOrder(root->left);
	PostOrder(root->right);
	post.push_back(root->data);
}

void PostOrderMirror(node* root) {
	if (root == NULL)
		return;
	PostOrderMirror(root->right);
	PostOrderMirror(root->left);
	post.push_back(root->data);
}

int main() {
	int n, data;
	scanf("%d", &n);
	node* root = NULL; //root是一个空指针,因为还没有插入数据
	for (int i = 0; i < n; i++) {
		scanf("%d", &data);
		insert(root, data);
		origin.push_back(data);
	}
	PreOrder(root);
	PreOrderMirror(root);
	if (origin == pre) {
		printf("YES\n");
		PostOrder(root);
		for (auto it = post.begin(); it != post.end(); it++) {
			if (it != post.begin())
				printf(" %d", *it);
			else
				printf("%d", *it);
		}
	}
	else if (origin == pre_mirror) {
		printf("YES\n");
		PostOrderMirror(root);
		for (auto it = post.begin(); it != post.end(); it++) {
			if (it != post.begin())
				printf(" %d", *it);
			else
				printf("%d", *it);
		}
	}
	else {
		printf("NO\n");
	}
}

 

鱼鹰优化算法(OOA)详解:从猛禽捕食智能到优化算法实现 鱼鹰优化算法(Osprey Optimization Algorithm, OOA)是2023年提出的一种新型元启发式优化算法,灵感来源于鱼鹰(一种中型猛禽)高效的捕食策略。算法模拟了鱼鹰从空中识别水下鱼类位置并俯冲捕食,然后将捕获的鱼带至安全位置享用的全过程,以此抽象出全局探索和局部开发两个核心阶段。OOA算法具有参数少、结构简单、收敛速度快、全局寻优能力强等特点。自提出以来,已在函数优化、机器学习参数调优(如CatBoost模型)、路径规划等多个领域展现出良好性能,为解决复杂优化问题提供了新的有效工具。 阅读详情

相关推荐

从零到一:基于PX4+Gazebo+ROS2的无人机轨迹跟踪仿真环境全栈搭建

本文详细介绍了在Ubuntu 22.04系统上,从零开始搭建基于PX4、Gazebo Garden和ROS2 Humble的无人机轨迹跟踪仿真环境的完整流程。内容涵盖PX4 SITL编译、Gazebo安装、ROS2配置、Micro XRCE-DDS Agent通信桥接以及QGroundControl地面站部署,并提供了创建自定义ROS2节点实现圆形轨迹跟踪的实战代码与关键调试技巧,帮助开发者快速构建全栈仿真开发环境。

swift5iosmith的博客 915

PAT甲级2014秋季全解

PAT甲级2014秋季1. Broken Keyboard2. Perfect Sequence3. Tree Traversals Again4. All Roads Lead to Rome 1. Broken Keyboard On a broken keyboard, some of the keys are worn out. So when you type some sentences, the characters corresponding to those keys will not a

all23333333的博客 387

Python入门之机器学习(非常详细)篇幅拉满,一般人看不完!

什么是机器学习?监督学习 supervised learning;非监督学习 unsupervised learning;半监督学习 semi-supervised learning;强化学习 reinforcement learning;监督学习是不断向计算机提供数据(特征),并告诉计算机对应的值(标签),最后通过大量的数据,让计算机自己学会判断和识别。例如Google Photo,你在APP中输入狗,这时就会弹出与狗相关的图片,这背后使用的算法就是监督学习。

xiaolinyui的博客 2万+

《算法笔记》3.1小节——入门模拟 问题 E: Shortest Distance (20)

题目描述 The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits. 输入 Each input file contains one test ca...

hwyu_95的博客 281

为什么你的PROFINET IRT同步性能不达标?等时模式常见配置误区盘点

本文深入剖析了PROFINET IRT等时模式同步性能不达标的常见原因。文章直击痛点,系统盘点了从硬件兼容性、拓扑组态、过程映像分区分配,到同步OB配置、时序参数调校及带宽管理等关键环节的配置误区,并提供了实用的诊断思路与性能优化清单,帮助工程师精准定位并解决同步抖动、时序混乱等难题。

ujm5678901的博客 457

L3 级自动驾驶 2025:法规突破与车企技术路线竞争

2025年L3级自动驾驶迎来规模化商业落地关键期。全球主要经济体在法规、技术、市场三方面取得突破:中国通过《北京市自动驾驶汽车条例》明确责任划分,欧盟设立严格技术认证标准。技术路线呈现"多传感器融合为主流,纯视觉为补充"格局,华为、特斯拉等企业展开硬件军备竞赛与算法架构革新。中国车企在技术验证和规模化应用方面领先,而欧美车企侧重生态整合。尽管面临成本控制、责任认定和用户信任等挑战,随着技术进步和车路协同发展,L3自动驾驶正从高端选配向大众化普及迈进,为L4级奠定基础。

2301_77933942的博客 3098

1075 PAT Judge

题目来源:PAT (Advanced Level) Practice The ranklist of PAT is generated from the status list, which shows the scores of the submissions. This time you are supposed to generate the ranklist for PAT. Input Specification: Each input file contains one test case

weixin_51032998的博客 242

Doorbell机制在PCI与MSI中断中的高效应用

本文深入解析了Doorbell机制在PCIe设备与CPU间通信中的核心作用。作为一种高效的硬件通知机制,它通过内存映射I/O(MMIO)实现软件对硬件的轻量级触发,常与MSI中断协同工作,构建高效的生产者-消费者模型。文章以AMD GPU的Ring Buffer命令提交为例,阐述了该机制如何显著降低CPU开销、提升系统吞吐量,并对比了其与传统中断方式的性能优势。

ee345的博客 610

【PAT刷题甲级】1075.PAT Judge

1075 PAT Judge (25 分) The ranklist of PAT is generated from the status list, which shows the scores of the submissions. This time you are supposed to generate the ranklist for PAT. Input Specification Each input file contains one test case. For each case,

C_greenbird的博客 430

机器人在果园内行巡检仿真(2D雷达、realsense相机)

DiffBot是一种具有两个轮子的自主差动驱动机器人。它的主要处理单元是一个运行Ubuntu Mate 20.04和ROS 1 (ROS Noetic)中间件的Raspberry pi4b。该存储库包含ROS驱动包、真实机器人的ROS控制硬件接口和模拟DiffBot的配置。修改配置文件orchard_world.launch。

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

机器人视觉联动精度优化:从±2mm到±0.02mm,产线级手眼标定全实战

2025年我接东莞长安Type-C接口分拣项目的时候,就是栽在了手眼标定上:实验室里标定完精度±0.5mm,一到产线直接掉到±2mm,机器人10次有3次抓不住,2000多件Type-C接口直接报废,还撞坏了2套汇川SCARA机器人的吸盘,本来45天的工期拖了3个月,不仅没赚到钱,还倒贴了几万块。手眼标定从来不是简单的跑个demo、算个矩阵就完事了,它是一个系统工程:从硬件选型、安装固定、相机标定、标定流程、算法优化、环境控制、重复验证,每一个环节都会影响最终的联动精度。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 386

2021-11-04 PAT(6) 从简单题过渡到中等题

最近没做PAT了,有些忙,打算一个月激情冲刺PAT,目前就是偶尔做题。 1094 The Largest Generation (25 分) A family hierarchy is usually presented by a pedigree tree where all the nodes on the same level belong to the same generation. Your task is to find the generation with the largest po

Yiyan__的博客 749

SAP Event Mesh 简介

Get Started with Messaging for Decoupled Communication Step 1: What is the SAP Event Mesh service? SAP Event Mesh 是一种完全托管的服务,用于连接应用程序、服务和系统,以便它们可以通过消息和事件相互交互。 它通过引入中央消息代理取代了传统的点对点通信。 虽然点对点通信适用于在有限数量的发送方和接收方之间共享数据,但可扩展性很快就会成为一个问题。 SAP Event Mesh 解决了这个问题,并确保

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1243

PAT A1043 Is It a Binary Search Tree (25 分)

1043Is It a Binary Search Tree(25分) 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...

树叶子的博客 466

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

PAT A 甲级 1043 Is It a Binary Search Tree (25分)

1043 Is It a Binary Search Tree (25分) 吐槽 ……感觉二叉树是甲级里最难的一类题了……比图论还难。要变通和自己思考逻辑的部分实在太多了。 思路 首先这道题是“非常规”的,这题不是“这个二叉树是不是搜索树”,而是“这遍历有没有可能是某个搜索树的先序遍历”。正常情况下需要两种遍历才能确立一棵二叉树,但这道题却只给了一种遍历。 不过,“二叉搜索树”本身是有条件的,正是...

虚境的博客 244

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

【PAT甲级】1043 Is It a Binary Search Tree (25分)

解题过程的小记录,如有错误欢迎指出。 难度:四星(又是没看懂题目的一题) 小导航~题目分析注意点我的解题过程思路bug代码dalao的代码借鉴点 题目分析 给出一串数列,该数列是二叉搜查数的插入数列,按照插入顺序建立树后看这个数列是否是该数的先序遍历数列,或者是镜像先序遍历数列(镜像也就是左右子树交换) 注意点 不能采用BST的中序遍历数列是递增数列的特性结合先序序列,因为本题的数字有重复 插入建树注意返回值,和参数的引用 我的解题过程 思路 利用数列进行插入建立BST,同时把数列保存在vector数

SpicyChicken的自我修养 347

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

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

PAT A1043 Is It a Binary Search Tree (25 分)

题目: 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 righ...

xiao1guaishou的博客 398

[C++] PAT 1043 Is It a Binary Search Tree (25分)

Sample Input 1: 7 8 6 5 7 10 8 11 Sample Output 1: YES 5 7 6 8 11 10 8 Sample Input 2: 7 8 10 11 8 6 7 5 Sample Output 2: YES 11 8 10 7 5 6 8 Sample Input 3: 7 8 6 8 5 10 9 11 Sample Output 3: NO 题解 代码来源于《算法笔记》 #include <iostream> #inclu.

快乐de约定的博客 1997

[PAT]1043 Is It a Binary Search Tree (25 分)

一、题意 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 ri...

刘好念的博客 329

PAT A1043 Is It a Binary Search Tree(25 分)

  1043 Is It a Binary Search Tree(25 分) 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 ke...

qq_20565303的专栏 427

【PAT 甲级】A1043 Is It a Binary Search Tree(25分)

PAT坑点提示!(当然也可能是我太笨了qwq):定义全局变量的时候一定不要用index这个标识符,否则会提示编译错误!! 原因貌似是用了#include <bits/stdc++.h>,这个头文件貌似已经定义了一些标识符,所以冲突了。当然我在Dev-C++上还是运行良好的… 【版本一:没读明白题就做了,死得很惨,17分】 代码不展示了,连给的样例测试点2都没过hhhh 【版本二:这个题...

weixin_42278063的博客 268

PAT 1043 Is It a Binary Search Tree (25分)

题目: 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 grea

qq_42593220的博客 300

PAT 甲级 1043 Is It a Binary Search Tree (25分)

题目 1043 Is It a Binary Search Tree (25分) 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

qq_41001689的博客 161

PAT甲级-1043 Is It a Binary Search Tree (25分)

点击链接PAT甲级-AC全解汇总 题目: 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...

卷子的博客 336

PAT A1043 Is It a Binary Search Tree (25分)

PAT A1043 Is It a Binary Search Tree 25分原题大体题意思路代码运行结果 原题 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

kyln1039的博客 176

PAT A 1043 Is It a Binary Search Tree (25 分)

二叉树结构处理

Siumai's Blog 196
上一篇: 1053 Path of Equal Weight (30 分)
下一篇: 拉伸试样尺寸设计
DedicateToAI
博客等级 码龄9年 6粉丝 90原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值