#include<iostream>
#include<vector>
using namespace std;
const int N = 1010;
vector<int> a,pre,post;
struct Tree{
int val;
Tree *left,*right;
Tree(int x){
val = x;
left = right = NULL;
}
};
void build(Tree* &t,int x){
if(!t){
t = new Tree(x);
return;
}
if(t->val <= x) build(t->right,x);
else build(t->left,x);
}
void pre1(Tree* t){
if(!t) return;
pre.push_back(t->val);
pre1(t->left);
pre1(t->right);
post.push_back(t->val);
}
void pre2(Tree* t){
if(!t) return;
pre.push_back(t->val);
pre2(t->right);
pre2(t->left);
post.push_back(t->val);
}
int main(){
int n;
Tree *bt = NULL;
cin>>n;
for(int i = 1; i <= n; i++){
int x;
cin>>x;
a.push_back(x);
build(bt,x);//不管是否为镜像,先建立搜索树
}
pre1(bt);//正搜索树先序遍历,并记录后序遍历
if(pre == a){
cout<<"YES\n";
for(int i = 0; i < post.size(); i++){
if(i) cout<<' ';
cout<<post[i];
}
return 0;
}
pre.clear(); post.clear();
pre2(bt);//镜像搜索树先序遍历,并记录后序遍历
if(pre == a){
cout<<"YES\n";
for(int i = 0; i < post.size(); i++){
if(i) cout<<' ';
cout<<post[i];
}
return 0;
}
cout<<"NO";
return 0;
}
7-28 搜索树判断 (25 分)
最新推荐文章于 2024-05-16 03:02:27 发布