题目链接 https://pintia.cn/problem-sets/994805046380707840/problems/994805069361299456
题目
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
AC代码
#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
typedef struct node
{
struct node *lc;
struct node *rc;
int date;
}bintree,*tree;
void createtree(int *in,int *po,int len,tree &T)
{
if(len==0){
T=NULL;
return;
}
T=new bintree;
T->date=*po;
int len1=0;
for(;len1<len;len1++){
if(in[len1]==*po)
break;
}
createtree(in,po-(len-len1),len1,T->lc);
createtree(in+len1+1,po-1,len-len1-1,T->rc);
}
void print(tree T)
{ int flog=0;
queue<tree> q;
q.push(T);
while(!q.empty()){
if(flog) cout<<" ";
flog=1;
T=q.front();
printf("%d",T->date);
q.pop();
if(T->lc) q.push(T->lc);
if(T->rc) q.push(T->rc);
}
cout<<endl;
}
int main()
{
int n;
cin>>n;
int po[55],in[55];
for(int i=0;i<n;i++)
scanf("%d",&po[i]);
for(int i=0;i<n;i++)
scanf("%d",&in[i]);
tree T;
createtree(in,(po+n-1),n,T);
print(T);
return 0;
}