给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> in,post,ans;
struct t_node{
int t_n;
t_node* t_l;
t_node* t_r;
};
queue<t_node*> q;
t_node* creatnode(int n){
t_node* nd=(t_node *)malloc(sizeof(t_node));
nd->t_n=n;
nd->t_l=NULL;
nd->t_r=NULL;
return nd;
}
t_node* buildtree(vector<int> z,vector<int> h){
if(z.empty()&&h.empty())return NULL;
t_node* root=creatnode(h[h.size()-1]);
int i;
vector<int>zl,zr,hl,hr;
for(i=0;i<z.size();i++){
if(h[h.size()-1]==z[i])break;
}
for(int j=0;j<i;j++){
zl.push_back(z[j]);
hl.push_back(h[j]);
}
for(int j=i+1;j<z.size();j++){
zr.push_back(z[j]);
hr.push_back(h[j-1]);
}
root->t_l=buildtree(zl,hl);
root->t_r=buildtree(zr,hr);
return root;
}
void cx(t_node* root){
q.push(root);
while(!q.empty()){
t_node* now=q.front();
q.pop();
ans.push_back(now->t_n);
if(now->t_l)q.push(now->t_l);
if(now->t_r)q.push(now->t_r);
}
}
int main(){
int n,a;
cin>>n;
for(int i=0;i<n;i++){
cin>>a;
post.push_back(a);
}
for(int i=0;i<n;i++){
cin>>a;
in.push_back(a);
}
t_node* root=buildtree(in,post);
cx(root);
for(int i=0;i<ans.size();i++){
cout<<ans[i];
if(i!=ans.size()-1)cout<<" ";
}
cout<<endl;
return 0;
}
十分基础的建树遍历。