输入:总的结点个数n
中序序列
后序序列
输出:层次遍历序列
注意输出的最后没有空格
测试样例:
输入:
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 <queue>
#include <algorithm>
using namespace std;
const int MAX=50;
struct Node
{
int val;
Node* lchild;
Node* rchild;
Node(int a)
{
val=a;
lchild=NULL;
rchild=NULL;
}
Node()
{
val=0;
lchild=NULL;
rchild=NULL;
}
};
int in[MAX],post[MAX];
int n;
//传入后序序列及其起始坐标,中序序列及其起始坐标,总的结点数
Node* createTree(int post[],int i,int in[],int j,int n)
{
Node* t;
int ch;
int p,k;
if(n<=0) return NULL;
ch=post[i+n-1];//根结点
t=new Node(ch);
p=j;//临时记录头结点位置
while(p<j+n)//寻找根结点
{
if(in[p]==ch)
break;
p++;
}
k=p-j;//左子树的长度
t->lchild=createTree(post,i,in,j,k);
t->rchild=createTree(post,i+k,in,p+1,n-k-1);
return t;
}
void BFS(Node* root)
{
int num=0;//用来记录当前的结点的个数,作用是确保输出的最后没有空格
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node* now=q.front();
q.pop();
cout<<now->val;
num++;
if(num<n) cout<<" ";//确保最后一个输出的后面没有空格
if(now->lchild) q.push(now->lchild);
if(now->rchild) q.push(now->rchild);
}
}
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=createTree(post,0,in,0,n);
BFS(root);
return 0;
}