7-10 树的遍历(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
其实build不出来return 0会比较好,memset也全化为0,可以稍微简化一下代码
从build里面可以学会:表示两个元素一样,顺序却不一样(又不能打乱它的顺序)的集合的时候,可以试着用元素个数表示。
认真看代码,学会里面的一万种技巧。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<set>
#include<queue>
typedef long long ll;
using namespace std;
const int maxn = 100 + 10;
int post[maxn], in[maxn];
int rch[maxn], lch[maxn];
int build(int l1, int r1, int l2, int r2){//post[l1...r1],in[l2...r2]
if(l1 > r1 || l2 > r2) return -1;
int root = post[r1];
int p = 0;
while(in[l2+p] != root) p++;//p为左子树节点个数
lch[root]=build(l1,l1+p-1 ,l2, l2+p-1);//建立左子树
rch[root]=build(l1+p, r1-1, l2+p+1, r2);//建立右子树
return root;
}
void bfs(int root){
queue<int>q;
q.push(root);
while(!q.empty()){
int tn = q.front();
printf("%d", tn);
q.pop();
if(lch[tn] > 0){
q.push(lch[tn]);
}
if(rch[tn] > 0){
q.push(rch[tn]);
}
if(q.size()!= 0) printf(" ");
}
return;
}
int main(){
int n;
scanf("%d", &n);
memset(rch, -1, sizeof(rch));
memset(lch, -1, sizeof(lch));
for(int i = 0; i < n; i++)scanf("%d", &post[i]);
for(int i = 0; i < n; i++)scanf("%d", &in[i]);
int root = build(0, n-1,0 , n-1);
//for(int i = 1; i <= n; i++) printf("lch[%d] = %d, rch[%d] = %d
", i, lch[i], i, rch[i]);
bfs(root);
return 0;
}