题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1043
// 之前写建树的代码都不标准
// 本题的思路,参考了同学的思想:
// 如果不符合条件,建树终止,后执行一次遍历,
// 树的节点不足n,则代表建树失败。
#include <stdio.h>
#include <iostream>
#include <vector>
#define SIZE 100000+10
using namespace std;
struct Node
{
Node *lc;
Node *rc;
int value;
};
// normal
Node * build_bin_tree1(int s, int e, vector<int> preorder)
{
if (s > e) return NULL;
Node *root = new Node();
root->value = preorder[s];
int i;
for(i = s+1; i<= e; i++)
{
if(preorder[i] >= preorder[s])
{
break;
}
}
// check
for(int j = i; j <= e; j++)
{
if(preorder[j] < preorder[s])
{
return NULL;
}
}
root->lc = build_bin_tree1(s+1, i-1, preorder);
root->rc = build_bin_tree1(i, e, preorder);
return root;
}
// mirror
Node * build_bin_tree2(int s, int e, vector<int> preorder)
{
if (s > e) return NULL;
Node *root = new Node();
root->value = preorder[s];
int i;
for(i = s+1; i <= e; i++)
{
if(preorder[i] < preorder[s])
{
break;
}
}
for(int j=i; j<=e; j++)
{
if(preorder[j] >= preorder[s])
{
return NULL;
}
}
root->lc = build_bin_tree2(s+1, i-1, preorder);
root->rc = build_bin_tree2(i, e, preorder);
return root;
}
void post_order(Node * root, vector<int> &postorder)
{
if(root == NULL) return;
post_order(root->lc, postorder);
post_order(root->rc, postorder);
postorder.push_back(root->value);
}
void Output(vector<int> order)
{
int i;
for(i = 0; i < order.size(); i++)
{
printf("%d ", order[i]);
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
#endif
int n;
while(scanf("%d", &n) != EOF)
{
vector<int> preorder;
while(n-->0)
{
int t;
scanf("%d", &t);
preorder.push_back(t);
}
//creating tree
Node * T1 = build_bin_tree1(0, preorder.size()-1, preorder);
Node * T2 = build_bin_tree2(0, preorder.size()-1, preorder);
//get postorder
vector<int> postorder1, postorder2;
post_order(T1, postorder1);
post_order(T2, postorder2);
//check and output
if(postorder1.size() < preorder.size() && postorder2.size() < preorder.size())
{
printf("NO\n");
continue;
}
printf("YES\n");
if(postorder1.size() == preorder.size())
{
// printf("Normal\n");
int i;
for(i=0; i<postorder1.size()-1; i++)
{
printf("%d ", postorder1[i]);
}
printf("%d\n", postorder1[postorder1.size()-1]);
}
else if(postorder2.size() == preorder.size())
{
// printf("Mirror\n");
int i;
for(i=0; i<postorder2.size()-1; i++)
{
printf("%d ", postorder2[i]);
}
printf("%d\n", postorder2[postorder2.size()-1]);
}
}// while
return 0;
}