由于是前序,所以根节点始终是第一个,不管镜像与否,都可以直接建树。
#include <iostream>
#include <cstdio>
#include <stack>
#include <string>
#include <cctype>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> pre, post, input, pree, postt;
struct tree{
int val;
tree* left, *right;
tree(int x){
val = x;
left = right = nullptr;
}
};
void create(tree* & root, int x){
if(!root){
root = new tree(x);
}else if(root->val <= x)
create(root->right, x);
else create(root->left, x);
}
void order1(tree* root){
if(!root) return;
pre.push_back(root->val);
order1(root->left);
order1(root->right);
post.push_back(root->val);
}
void order2(tree* root){
if(!root) return;
pree.push_back(root->val);
order2(root->right);
order2(root->left);
postt.push_back(root->val);
}
int main(){
int n, x;
cin>>n;
tree* root = nullptr;
for(int i = 0; i < n; i++){
cin>>x;
input.push_back(x);
create(root, x);
}
order1(root);
if(pre == input){
cout<<"YES"<<endl;
for(int i = 0; i < n; i++){
if(i) cout<<" ";
cout<<post[i];
}
}else{
order2(root);
if(pree == input){
cout<<"YES"<<endl;
for(int i = 0; i < n; i++){
if(i) cout<<" ";
cout<<postt[i];
}
}else cout<<"NO";
}
return 0;
}