给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
该题主要考察通过后序和中序来求树的过程。注意结合通过前序和中序来理解。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<math.h>
#include<queue>
#include <set>
using namespace std;
typedef long long int LL;
struct Tree{
int index;
struct Tree *l=NULL,*r=NULL;
};
int behind[31];
int in[31];
void build(int left,int right,int &t,Tree *&root)
{
int flag=-1;
for(int i=left;i<=right;i++)
if(in[i]==behind[t])
{ flag=i;
break;
}
if(flag==-1)
{root=NULL;
return;}
root=(struct Tree *)malloc(sizeof(struct Tree));
root->index=in[flag];
t--;
if(flag<right)build(flag+1,right,t,root->r);
if(flag>left)build(left,flag-1,t,root->l);
return ;
}
void lineorder(struct Tree *root) {
queue<struct Tree *> a;
a.push(root);
int flag=0;
while (!a.empty())
{ struct Tree *obj;
obj=a.front();
a.pop();
if(flag!=0)
cout<<" ";
cout<<obj->index;flag++;
if(obj->l!=NULL)a.push(obj->l);
if(obj->r!=NULL)a.push(obj->r);
}
return ;
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>behind[i];
for(int i=0;i<n;i++)
cin>>in[i];
Tree *root=(struct Tree *)malloc(sizeof(struct Tree));
int t=n-1;
build(0,n-1,t,root);
lineorder(root);
return 0;
}