题目:
输入n代表二叉树节点数量,接下来两行分边n个整数,代表二叉树的后序遍历和中序遍历
输出层次遍历的顺序
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <iomanip>
using namespace std;
//#pragma comment(linker, "/STACK:102400000,102400000")
#define maxn 10050
#define MOD 1000000007
#define mem(a , b) memset(a , b , sizeof(a))
#define LL long long
#define ULL unsigned long long
typedef pair<int , int> pii;
const long long INF= 0x3fffffff;
int last[maxn] , mid[maxn];
int a[maxn] , b[maxn];
struct node
{
int l , r , val;
}tmp , ans[maxn];
int res[maxn] , id;
void solve1(int root , int l1 , int r1 , int l2 , int r2); //给定左子树的区间
void solve2(int root , int l1 , int r1 , int l2 , int r2) //给定右子树的期间
{
//cout << root << endl;
if(r1 < l1 || l1 > r1 || r2 < l2 || l2 > r2)
{
ans[root].r = -1;
return;
}
if(l1 == r1)
{
ans[root].r = a[r1];
return ;
}
ans[root].r = a[r1];
solve1(ans[root].r , l1 , l1 + mid[a[r1]] - l2 - 1 , l2 , mid[a[r1]] - 1 );
solve2(ans[root].r , l1 + mid[a[r1]] - l2 , r1 - 1 , mid[a[r1]]+1 , r2);
}
void solve1(int root , int l1 , int r1 , int l2 , int r2)
{
//cout << root << endl;
if(r1 < l1 || l1 > r1 || r2 < l2 || l2 > r2)
{
ans[root].l = -1;
return;
}
if(l1 == r1)
{
ans[root].l = a[r1];
return ;
}
ans[root].l = a[r1];
solve1(ans[root].l , l1 , l1 + mid[a[r1]] - l2 - 1 , l2 , mid[a[r1]] - 1 );
solve2(ans[root].l , l1 + mid[a[r1]] - l2 , r1-1 , mid[a[r1]] +1 , r2);
}
void BFS(int root)
{
queue<int>q;
while(!q.empty()) q.pop();
q.push(root);
while(!q.empty())
{
int val = q.front();
q.pop();
res[id++] = val;
if(ans[val].l != -1) q.push(ans[val].l);
if(ans[val].r != -1) q.push(ans[val].r);
// cout << val << " " << ans[val].l << " " << ans[val].r << endl;
}
}
int main()
{
int n , m , num , l , r;
while(scanf("%d" , &n) != EOF)
{
id = 0;
mem(last , 0);
mem(mid , 0);
mem(ans , -1);
for(int i = 1 ; i <= n ; i ++)
{
scanf("%d" , &a[i]);
last[a[i]] = i;
}
for(int i = 1 ; i <= n ; i ++)
{
scanf("%d" , &b[i]);
mid[b[i]] = i;
}
int root = a[n];
solve1(a[n] , 1 , mid[root]-1 , 1 , mid[root] - 1);
solve2(a[n] , mid[root] , n-1 , mid[root] + 1 , n);
// cout << "YES" << endl;
BFS(root);
for(int i = 0 ; i < id ; i ++)
{
printf("%d" , res[i]);
if(i != id -1) printf(" ");
}
cout << endl;
}
return 0;
}