题意:
给出一棵二叉树的后序遍历序列和中序遍历序列,求这棵二叉树的层序遍历序列。
思路:
后序、中序转层序与后序、中序转前序差不多,主要是我们需要一个index来记录层次遍历中结点的序号。
代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int post[35];//后序序列
int in[35];//中序序列
int n;//结点个数
int cnt=0;
struct node{
int index;
int key;
}level[35];
bool cmp(node a,node b){
return a.index<b.index;
}
void level_output(int root,int start,int ends,int index){//层序打印
if(start>ends){
return;
}
int i=start;
while(i<ends&&in[i]!=post[root]){//找到中序序列中根结点的位置
i++;
}
level[cnt].key=post[root];
level[cnt].index=index;
cnt++;
level_output(root-(ends-i+1),start,i-1,2*index+1);//遍历左子树
level_output(root-1,i+1,ends,2*index+2);//遍历右子树
}
int main(){
cin>>n;
for(int i=0;i<n;i++){//读入后序序列
cin>>post[i];
}
for(int i=0;i<n;i++){
cin>>in[i];
}
level_output(n-1,0,n-1,0);
sort(level,level+n,cmp);
for(int i=0;i<n;i++){
if(i!=n-1){
cout<<level[i].key<<' ';
}else{
cout<<level[i].key;
}
}
return 0;
}
当然,也可以选择建树的做法:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<cmath>
#include<queue>
#include<cstring>
#include<vector>
#include<stack>
#include<map>
#define MAX 1000005
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
int n,cnt=0;//节点个数
int post[35],in[35];
struct node{
int key;
node *left;
node *right;
};
void level_output(node* root){//层序打印
queue<node *>q;
q.push(root);//根节点入队
while(!q.empty()){
node *top=q.front();
q.pop();
printf("%s%d",cnt==0?"":" ",top->key);
if(!cnt) cnt++;
if(top->left!=NULL) q.push(top->left);
if(top->right!=NULL) q.push(top->right);
}
}
node* build_tree(int r,int start,int ends){
if(start>ends){
return NULL;
}
int i=start;
while(i<ends&&post[r]!=in[i]) i++;
node *root=(node *)malloc(sizeof(node));
root->key=post[r];
root->left=build_tree(r-(ends-i+1),start,i-1);
root->right=build_tree(r-1,i+1,ends);
return root;
}
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=build_tree(n-1,0,n-1);
level_output(root);
return 0;
}