题目描述:
假设二叉树中的所有键都是不同的正整数。给定后序和中序遍历序列,你应该输出相应二叉树的层序遍历序列。
输入格式:
每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数N(≤30),即二叉树中的节点总数。第二行给出后序序列,第三行给出中序序列。一行中的所有数字用一个空格隔开。
输出格式:
对于每个测试用例,在一行中打印相应二叉树的层次顺序遍历序列。一行中的所有数字必须用一个空格隔开,并且行尾不能有多余的空格。
样例输入:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
样例输出:
4 1 6 3 5 7 2
思路:
根据后序和中序遍历序列构建出二叉树,然后进行层序遍历即可。假设递归过程中某步的后序序列区间为[postL,postR],中序序列区间为[inL,inR],由后序序列的性质可知,后序序列的最后一个元素为根节点。接着就可以在中序序列中找到这个根节点,中序序列中根节点左边区间的为左子树上的节点,右边的为右子树上的节点。假设在中序序列中in[k]为根节点,那么左子树节点的个数为numLeft = k-inL。因此,左子树的后序序列区间为[postL,postL+numLeft-1],左子树的中序遍历区间为[inL,k-1];右子树的后序遍历区间为[postL+numLeft,postR-1],右子树的中序遍历区间为[k+1,inR]
代码:
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 50;
struct node{
int data;
node* lchild;
node* rchild;
};
int pre[maxn],in[maxn],post[maxn];//先序,中序,后序
int n;//节点个数
//当前二叉树的后序序列区间为[postL,postR],中序序列区间为[inL,inR]
//create函数返回构建出的二叉树的根节点的地址
node* create(int postL,int postR,int inL,int inR){
if(postL > postR)
return NULL;//后序序列长度小于等于0时,直接返回
node* root = new node;
root->data = post[postR];
int k;
for(k = inL ; k <= inR ; k++){
if(in[k]==post[postR]){
break;//在中序遍历中找到根节点
}
}
int numLeft = k - inL;//左子树节点的个数
root->lchild = create(postL,post+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* now = q.front();
q.pop();
printf("%d",now->data);
num++;
if(num < n)
printf(" ");
if(now->lchild!=NULL)
q.push(now->lchild);
if(now->rchild!=NULL)
q.push(now->rchild);
}
}
int main(){
scanf("%d",&n);
for(int i = 0 ; i < n ; i++)
scanf("%d",&post[i]);
for(int i = 0 ; i < n ; i++)
scanf("%d",&in[i]);
node* root = create(0,n-1,0,n-1);//建树
BFS(root);
return 0;
}