Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences, or preorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.
Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 30), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, first printf in a line Yes
if the tree is unique, or No
if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input 1:
7
1 2 3 4 6 7 5
2 6 7 4 5 3 1
Sample Output 1:
Yes
2 1 6 4 7 3 5
Sample Input 2:
4
1 2 3 4
2 4 3 1
Sample Output 2:
No
2 1 3 4
给定我们 MLR 和 LRM 序,让我们确定任意一颗 满足要求的二叉树。
关键: 枚举左子树可能的长度值,看看是不是满足要求。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define rep(i,a,b) for(int i=a;i<b;++i)
const int N=50;
int mlr[N],lrm[N];
struct Node{
int x;
Node* l,*r;
};
int res[N];
set<int> has;
int ok=1;
void build(Node* &rt,int* mlr,int* lrm,int len){
rt=new Node;
rt->x=mlr[0];
rt->l=rt->r=NULL;
if(len==2)ok=0;
if(len==1)return;
int i=0;
for(i=0;i<len;i++)if(lrm[i]==mlr[1])break;
has.clear();
for(int j=1;j<=i+1;j++)has.insert(mlr[j]);
int wrong=0;
for(int j=0;j<=i;j++){
if(!has.count(lrm[j])){
wrong=1;break;
}
}
if(!wrong){
build(rt->l,mlr+1,lrm,i+1);
if(i!=len-2)build(rt->r,mlr+i+1+1,lrm+i+1,len-1-(i+1));
}else{
build(rt->r,mlr+1,lrm,len-1);
}
}
int cnt=0;
void get_ans(Node* rt){
if(rt==NULL)return;
get_ans(rt->l);
res[cnt++]=rt->x;
get_ans(rt->r);
}
int main(){
int n;
scanf("%d",&n);
rep(i,0,n)scanf("%d",&mlr[i]);
rep(i,0,n)scanf("%d",&lrm[i]);
Node* rt=NULL;
ok=1;
build(rt,mlr,lrm,n);
get_ans(rt);
if(ok)printf("Yes\n");
else printf("No\n");
rep(i,0,n)printf("%d%c",res[i],i==n-1?'\n':' ');
return 0;
}