题目链接:
https://pintia.cn/problem-sets/994805342720868352/problems/994805440976633856
题目分析:
本题为二叉查找树,首先,根据输入序列,构建二叉排序树,我们知道输入序列即为前序序列。然后,判断是正常的二叉排序树还是mirror 二叉排序树。最后,输出该树的后序序列。
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
const int inf = 1e9; // 0x3f3f3f3f //#define pb push_back
const int N = 1005;
struct node
{
int data;
node *left,*right;
};
node *root = NULL;
int a[N], n;
vector<int> ans;
void insert(node* &root,int w) //建二叉查找树
{
if(root==NULL)
{
root=new node; //root=new node();
root->data=w;
root->left=root->right=NULL;
return;
}
if(w < root->data) insert(root->left,w);
else insert(root->right,w);
}
void preorder(node *root) //前序遍历
{
if(root==NULL)
return;
ans.push_back(root->data);
preorder(root->left);
preorder(root->right);
}
void postorder(node *root) //后序遍历
{
if(root==NULL)
return;
postorder(root->left);
postorder(root->right);
ans.push_back(root->data);
}
void postorder2(node *root)
{
if(root==NULL)
return;
postorder2(root->right);
postorder2(root->left);
ans.push_back(root->data);
}
void preorder2(node *root)
{
if(root==NULL)
return;
ans.push_back(root->data);
preorder2(root->right);
preorder2(root->left);
}
bool check()
{
for(int i=0;i<ans.size();i++)
if(ans[i] != a[i]) return false;
return true;
}
void print()
{
for(int i=0;i<ans.size();i++)
{
if(i) cout<<" ";
cout<<ans[i];
}
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i],insert(root,a[i]);
preorder(root);
if(check())
{
ans.clear();
printf("YES\n");
postorder(root);
print();
return 0;
}
ans.clear();
preorder2(root);
if(check())
{
ans.clear();
printf("YES\n");
postorder2(root);
print();
return 0;
}
cout<<"NO"<<endl;
return 0;
}
下面给出柳神的代码,真的简单。。。代码行数真少。
#include <cstdio>
#include <vector>
using namespace std;
bool isMirror;
vector<int> pre, post;
void getpost(int root, int tail) {
if(root > tail) return ;
int i = root + 1, j = tail;
if(!isMirror) {
while(i <= tail && pre[root] > pre[i]) i++;
while(j > root && pre[root] <= pre[j]) j--;
} else {
while(i <= tail && pre[root] <= pre[i]) i++;
while(j > root && pre[root] > pre[j]) j--;
}
if(i - j != 1) return ; //当不是正常的二叉排序树时,i-j != 0满足条件,此时post.size() != n
getpost(root + 1, j);
getpost(i, tail);
post.push_back(pre[root]);
}
int main() {
int n;
scanf("%d", &n);
pre.resize(n);
for(int i = 0; i < n; i++)
scanf("%d", &pre[i]);
getpost(0, n - 1);
if(post.size() != n) {
isMirror = true;
post.clear();
getpost(0, n - 1);
}
if(post.size() == n) {
printf("YES\n%d", post[0]);
for(int i = 1; i < n; i++)
printf(" %d", post[i]);
} else {
printf("NO");
}
return 0;
}