题意:已知后序遍历和中序遍历,构造树,然后输出层序遍历(用bfs)
#include <bits/stdc++.h>
using namespace std;
const int maxn=35;
int n;
int post[maxn];
int in[maxn];
typedef struct node{
int val;
struct node *lchild;
struct node *rchild;
}node;
node *buildTree(int pl,int pr,int il,int ir)
{
if(pl>pr)
return NULL;
//因为后序遍历的最后一个结点一定为根,先找到根,然后根据中序遍历划分出左右子树,在循环此查找
int t=0;
while(in[t]!=post[pr])
t++;
node *binode = (node*)malloc(sizeof(node));
binode->val = post[pr];
binode->lchild = buildTree(pl,pl+t-il-1,il,t-1);
binode->rchild = buildTree(pl+t-il,pr-1,t+1,ir);
return binode;
}
void bfs(node *root)
{
queue<node *>q; //队列元素用结构体指针
node *temp=NULL;
q.push(root);
int f=0;
while(!q.empty()){
temp=q.front();
q.pop();
if(temp){
if(!f){
cout<<temp->val;
f=1;
}
else{
cout<<" "<<temp->val;
}
q.push(temp->lchild);
q.push(temp->rchild);
}
}
cout<<endl;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
cin>>post[i];
for(int i=0;i<n;i++)
cin>>in[i];
node *root;
root=buildTree(0,n-1,0,n-1);
bfs(root);
return 0;
}