给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
本题是考察树的基础知识的一题,思路:先根据后序序列和中序序列构造二叉树,然后再利用队列实现层次遍历,返回结果集,最后输出结果集即可。注意:构造二叉树的过程是递归的。
//@author:hairu,wu
//@from:ahut
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
const int max_n=100;
int n;
int last[max_n];
int in[max_n];
struct Tree{
int data;
Tree *lchild;
Tree *rchild;
Tree(){
lchild=rchild=NULL;
}
};
void createTree(Tree* &t,int abegin,int aend,int bbegin,int bend){
if(abegin>aend) return ;
if(t==NULL){
t=new Tree();
t->data=last[aend];
}
int tmp=last[aend];
int i=bbegin;
for(i=bbegin;i<=bend;i++){
if(in[i]==tmp){
break;
}
}
createTree(t->lchild,abegin,abegin+(i-bbegin-1),bbegin, i-1);//左子树
createTree(t->rchild,abegin+(i-bbegin),aend-1,i+1,bend);//右子树
}
//先序遍历
void preorder(Tree *t){
if(t==NULL) return ;
cout<<t->data<<" ";
preorder(t->lchild);
preorder(t->rchild);
}
//层次遍历
vector<int> levelorder(Tree *t){
vector<int> ans;
queue<Tree *> q;
q.push(t);
while(!q.empty()){
Tree *node=q.front();
q.pop();
ans.push_back(node->data);
if(node->lchild!=NULL) q.push(node->lchild);
if(node->rchild!=NULL) q.push(node->rchild);
}
return ans;
}
int main(){
//根据后序和中序来建立二叉树,并且输出层次遍历的结果
cin >>n;
for(int i=0;i<n;i++){
cin >> last[i];
}
for(int i=0;i<n;i++){
cin >> in[i];
}
Tree *tree=NULL;
createTree(tree,0,n-1,0,n-1);//建立二叉树
//preorder(tree);
vector<int> ans=levelorder(tree);
int size=ans.size();
for(int i=0;i<size;i++){
cout<<ans[i];
if(i!=size-1) cout<<" ";
else cout<<endl;
}
return 0;
}