给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=50;
struct node{
int data;
node* lchild;
node* rchild;
};
int in[maxn],post[maxn];//分别存储中序,和后序
int n;//结点个数
//通过后序遍历和中序遍历先把二叉树进行恢复
node* create(int postL,int postR,int inL,int inR)
{
if(postL>postR)
{
return NULL;
}
node* root=new node;//新建一个新的结点存放当前二叉树的根节点
root->data=post[postR];
int k;
for(k=inL;k<=inR;k++)
{
if(in[k]==post[postR])//找到根节点
break;
}
//通过k的定位找到根节点的位置,从而确定左子树和右子树的数据范围
int numleft=k-inL;
root->lchild=create(postL,postL+numleft-1,inL,k-1);
root->rchild=create(postL+numleft,postR-1,k+1,inR);
return root;//返回根节点位置
}
//将已经恢复的二叉树进行层序遍历,进行输出
int num=0;//已经输出的结点的个数
void BFS(node* root)
{
queue<node*>q;
q.push(root);//将根结点入队
while(!q.empty())
{
node* head = q.front();//取出队首元素
q.pop();
printf("%d",head->data);//访问队首元素
num++;
if(num<n)printf(" ");
if(head->lchild!= NULL) q.push(head->lchild);
if(head->rchild!=NULL)q.push(head->rchild);
}
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&post[i]);
}
for(int j=0;j<n;j++)
{
scanf("%d",&in[j]);
}
node* root=create(0,n-1,0,n-1);//恢复二叉树
BFS(root);//层序遍历
return 0;
}