当前位置:网站首页>搜索树判断 (25 分)
搜索树判断 (25 分)
2022-04-23 08:35:00 【怀化第二深情】
对于二叉搜索树,我们规定任一结点的左子树仅包含严格小于该结点的键值,而其右子树包含大于或等于该结点的键值。如果我们交换每个节点的左子树和右子树,得到的树叫做镜像二叉搜索树。
现在我们给出一个整数键值序列,请编写程序判断该序列是否为某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,如果是,则输出对应二叉树的后序遍历序列。
输入格式:
输入的第一行包含一个正整数N(≤1000),第二行包含N个整数,为给出的整数键值序列,数字间以空格分隔。
输出格式:
输出的第一行首先给出判断结果,如果输入的序列是某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,则输出YES
,否侧输出NO
。如果判断结果是YES
,下一行输出对应二叉树的后序遍历序列。数字间以空格分隔,但行尾不能有多余的空格。
输入样例1:
7
8 6 5 7 10 8 11
输出样例1:
YES
5 7 6 8 11 10 8
输入样例2:
7
8 6 8 5 10 9 11
输出样例2:
NO
#include<cstdio>
#include<vector>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
int g[1010];
vector<int>kp;
int n;
bool f;
void build(int l,int r){
if(l>r)return;
int i=r,j=l+1;
int t=g[l];
if(f){
while(g[i]>=t&&i>l)i--;
while(g[j]<t&&j<=r)j++;
}
else {
while(g[i]<t&&i>l)i--;
while(g[j]>=t&&j<=r)j++;
}
if(j-i!=1)return;
build(l+1,i);
build(j,r);
kp.push_back(t);
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>g[i];
}
build(0,n-1);
if(kp.size()!=n){
f=!f;
build(0,n-1);
}
if(kp.size()==n){
cout<<"YES\n";
cout<<kp[0];
for(int i=1;i<n;i++){
cout<<" "<<kp[i];
}
}
else cout<<"NO\n";
return 0;
}
版权声明
本文为[怀化第二深情]所创,转载请带上原文链接,感谢
https://blog.csdn.net/dege2929512534/article/details/124339339
边栏推荐
猜你喜欢
Notes on 30 steps of introduction to Internet of things of yangtao electronics STM32 III. Explanation of new cubeide project and setting
Overview of bus structure
Idea is configured to connect to the remote database mysql, or Navicat fails to connect to the remote database (solved)
xctf刷题小记
php基于哈希算法出现的强弱比较漏洞
Test your machine learning pipeline
正点原子携手OneOS直播 OneOS系统教程全面上线
ESP32程序下载失败,提示超时
Flash project cross domain interception and DBM database learning [Baotou cultural and creative website development]
[C语言] 文件操作《一》
随机推荐
Detailed description of self feeling of auricular point weight loss 0422
请问中衍期货安全靠谱吗?
Failed to convert a NumPy array to a Tensor(Unsupported Object type int)
MATLAB 画五星红旗
请提前布局 Star Trek突破链游全新玩法,市场热度持续高涨
MySQL查询两张表属性值非重复的数据
QT reading and writing XML files
Idea is configured to connect to the remote database mysql, or Navicat fails to connect to the remote database (solved)
LINQ学习系列-----1.4 匿名对象
STM32使用HAL库,整体结构和函数原理介绍
uni-app和微信小程序中的getCurrentPages()
正点原子携手OneOS直播 OneOS系统教程全面上线
【58】最后一个单词的长度【LeetCode】
Type anonyme (Principes fondamentaux du Guide c)
Ajax cache prevention method
Consensus Token:web3.0生态流量的超级入口
Ear acupoint diagnosis and treatment essay 0421
Excle plus watermark
Flink SQL实现流批一体
Notes on 30 steps of introduction to Internet of things of yangtao electronics STM32 III. Explanation of new cubeide project and setting