题目链接:https://www.patest.cn/contests/gplt/L2-011
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std;
#define INF 0x3f3f3f3f
#define N 50
int preorder[N], inorder[N];
int pre; //先序数组的指针,按先序遍历的结点次序依次建树,故设置为全局变量
typedef struct node
{
int data;
node *lchild;
node *rchild;
node()
{
lchild=NULL;
rchild=NULL;
}
}Node;
void build(Node *t,int inL,int inR)
{
int i=inL;
for(;i<inR;i++){
if(inorder[i]==preorder[pre])
break;
}
if(i>inL){ //t存在左子树
pre++;
Node *lc=new Node;
lc->data=preorder[pre];
t->lchild=lc;
build(lc,inL,i);
}
if(i<inR-1){ //t存在右子树
pre++;
Node *rc=new Node;
rc->data=preorder[pre];
t->rchild=rc;
build(rc,i+1,inR);
}
}
void Bfs(Node *t) //层次遍历的变形
{
queue<Node *> q;
printf("%d",t->data);
q.push(t);
while(!q.empty()){
Node *cur=q.front();
q.pop();
Node *rc=cur->rchild,*lc=cur->lchild;
if(rc){
printf(" %d",rc->data);
q.push(rc);
}
if(lc){
printf(" %d",lc->data);
q.push(lc);
}
}
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&inorder[i]);
for(int i=0;i<n;i++)
scanf("%d",&preorder[i]);
pre=0;
Node *t=new Node;//new会调用构造函数,而malloc不会
t->data=preorder[0];
build(t,0,n);
Bfs(t);
printf("\n");
return 0;
}