给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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 <bits/stdc++.h>
using namespace std;
struct ls{
ls* l;ls* r;
int n;
};
void fd(int *p,int* q,ls* x,int pl,int pr,int ql,int qr){
int t=p[pr-1],ql0=ql;
x->n=t;
while(ql0<qr&&q[ql0]!=t)ql0++; //找根
if(ql0!=ql){
ls *u=(ls*)malloc(sizeof(ls)); //新建一个节点
u->l=NULL;u->r=NULL;
x->l=u; //连上
fd(p,q,u,pl,pl+ql0-ql,ql,ql0); //递归
}
if(ql0!=qr-1){
ls *u=(ls*)malloc(sizeof(ls)); //新建一个节点
u->l=NULL;u->r=NULL;
x->r=u; //连上
fd(p,q,u,pl+ql0-ql,pr-1,ql0+1,qr);//递归
}
}
int main(void){
int n;
cin>>n;
vector<int> st;
int *p=(int*)malloc(sizeof(int)*n);
int *q=(int*)malloc(sizeof(int)*n);
ls *s=(ls*)malloc(sizeof(ls));
s->l=NULL;s->r=NULL;
for(int i=0;i<n;i++)cin>>p[i];
for(int i=0;i<n;i++)cin>>q[i];
fd(p,q,s,0,n,0,n);
queue<ls*> vs;
vs.push(s) ;
while(!(vs.empty())){
ls *temp=vs.front();vs.pop();
cout<<temp->n;
if(temp->l!=NULL)vs.push(temp->l);
if(temp->r!=NULL)vs.push(temp->r);
if(!vs.empty())cout<<' ';
}
return 0;
}