#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;
const int MAX = 50, INF = 1<<30;
typedef struct BiTNode
{
int data, height;
struct BiTNode *lChild, *rChild;
}BiTNode, *BiTree;
int Pre[MAX], Post[MAX], In[MAX];
int N, cnt = 0;
bool flag = 0;
void getIn(int preL, int preR, int postL, int postR)
{
if(preL == preR)
{
In[cnt++] = Pre[preL];
return ;
}
int k = preL+1;
while(k <= preR && Pre[k] != Post[postR-1]) k++;
if(k > preR) return ;
if(k - preL > 1) getIn(preL+1, k-1, postL, postL+k-preL-2);
else flag = 1;//此时该节点放在当前节点的左右子树都可以,这里放在了右子树
In[cnt++] = Pre[preL];//按中序存储
getIn(k, preR, postL+k-preL-1, postR-1);
}
int main()
{
scanf("%d", &N);
for(int i=0; i<N; i++) scanf("%d", &Pre[i]);
for(int i=0; i<N; i++) scanf("%d", &Post[i]);
getIn(0, N-1, 0, N-1);
if(flag) printf("No\n");
else printf("Yes\n");
printf("%d", In[0]);
for(int i=1; i<cnt; i++) printf(" %d", In[i]);
printf("\n");//头一次遇见最后没回车报格式错误的……
return 0;
}
PAT (Advanced Level) Practice A1119 Pre- and Post-order Traversals (30 分)(已知前序、后序求中序)
最新推荐文章于 2022-05-28 17:47:00 发布