Analysis : Binary tree, whether the pre-order and post-order are unique, and output in the order
#include<iostream>#include<vector>#include<string.h>#include<stdio.h>
using namespace std;typedefstruct node{
int left =-1;int right =-1;};
node node[31];int pre[31];int post[31];int is_u =1;voidbuild(int prel,int prer,int postl,int postr){
if(prel>=prer)return;int val = pre[prel+1];int index;for(int i = postl;i<=postr;i++){
if(val == post[i]){
index = i;break;}}int num = index - postl;if(num == prer-prel-1)
is_u =0;
node[prel].left = prel+1;// 不唯一 当做左孩子处理build(prel+1,prel+1+num,postl,index);if(prer-prel-1!= num)//唯一 有右孩子{
node[prel].right = prel+1+num+1;build(prel+1+num+1,prer,index+1,postr);}}int first =1;voidinorder(int root){
if(root==-1)return;inorder(node[root].left);if(first){
first =0;printf("%d",pre[root]);}else{
printf(" %d",pre[root]);}inorder(node[root].right);}intmain(){
int n;scanf("%d",&n);for(int i =1;i<=n;i++)scanf("%d",&pre[i]);for(int i =1;i<=n;i++)scanf("%d",&post[i]);build(1,n,1,n);if(is_u)printf("Yes\n");elseprintf("No\n");inorder(1);printf("\n");return0;}