1.题目
L2-006 树的遍历
分数 25
全屏浏览
切换布局
作者 陈越
单位 浙江大学
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
2.分析
因为要输出中序遍历,就要构建二叉树。构建二叉树可以是动态(有指针)或静态。静态的缺点是占用空间大(如果树右斜)结点下标为2的指数倍。但这道题的数据范围是小于30,而且动态二叉树我还没精通,用静态的也可以全过。
3.代码
#include<iostream>
#include<queue>
using namespace std;
const int MAX=10010;
//树的结构体数组
struct tree{
int l,r,w;
}e[MAX];
int N,s1[MAX], s2[MAX],n;
//建树操作
void display(int a, int b,int uns)
{
if (a>b) return;
e[uns].w=s1[n--];
e[uns].l=2*uns;
e[uns].r=2*uns+1; //结点下标成倍增长
int x;
for(x=a;x<=b;x++){
if(e[uns].w==s2[x]) break;
}
display(x+1,b,2*uns+1); //先右结点再左结点
display(a,x-1,2*uns);
}
//层序遍历
void bfs(){
int count=1;
queue<int> q;
q.push(count);
while(!q.empty()){
int x=q.front();
if(count==1) cout<<e[x].w;
else cout<<" "<<e[x].w;
q.pop();
if(e[e[x].l].w) q.push(e[x].l);
if(e[e[x].r].w) q.push(e[x].r);
count++;
}
}
int main()
{
cin >> N;
for (int i = 1; i <=N; i++){cin >> s1[i];}
for (int i = 1; i <=N; i++){cin >> s2[i];}
n=N;
display(1,N,1);
bfs();
return 0;
}