#include <bits/stdc++.h>
using namespace std;
vector<int >v;
vector<int>pre1;
vector<int>pre2;
vector<int>post1;
vector<int>post2;
struct Tnode
{
int data;
struct Tnode* left;
struct Tnode* right;
};
typedef struct Tnode* Btree;
Btree Insert(Btree &root,int x)//返回插入节点的位置
{
if(root==NULL)
{
Btree node=new struct Tnode;
node->data=x;
node->left=NULL;
node->right=NULL;
return node;
}
else if(x>=root->data)
{
root->right=Insert(root->right,x);
}
else if(x<root->data)
{
root->left=Insert(root->left,x);
}
return root;//返回那些不是空的节点的指针 最红返回根
}
void preorder1(Btree root)
{
if(!root)
return ;
else
{
/* pre.push_back(root->data);*/
pre1.push_back(root->data);
preorder1(root->left);
preorder1(root->right);
}
}
void preorder2(Btree root)//镜像树
{
if(!root)
return ;
else
{
/* pre.push_back(root->data);*/
pre2.push_back(root->data);
preorder2(root->right);
preorder2(root->left);
}
}
void postorder1(Btree root)
{
if(!root)
return ;
else
{
postorder1(root->left);
postorder1(root->right);
post1.push_back(root->data);
}
}
void postorder2(Btree root)
{
if(!root)
return ;
else
{
postorder2(root->right);
postorder2(root->left);
post2.push_back(root->data);
}
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;++i)
{
int num;
cin>>num;
v.push_back(num);
}
//还原BST树
Btree root=NULL;
for(int i=0;i<v.size();++i)
{
root=Insert(root,v[i]);
}
preorder1(root);
preorder2(root);
postorder1(root);
postorder2(root);
int f1=0,f2=0;
for(int i=0;i<n;++i)
{
if(v[i]!=pre1[i])
{
f1=1;
break;
}
}
for(int i=0;i<n;++i)
{
if(v[i]!=pre2[i])
{
f2=1;
break;
}
}
if(f1==0||f2==0)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO";
}
if(f1==0)//原树的先序遍历
{
int flag=1;
for(int i=0;i<post1.size();++i)
{
if(flag)
{
cout<<post1[i];
flag=0;
}
else
{
cout<<" "<<post1[i];
}
}
}
else if(f2==0) //镜像树的先序遍历
{
int f3=1;
for(int i=0;i<post2.size();++i)
{
if(f3)
{
cout<<post2[i];
f3=0;
}
else
{
cout<<" "<<post2[i];
}
}
}
}
https://pintia.cn/problem-sets/960414991140249600/problems/960415061227069444