视频讲解
https://www.bilibili.com/video/BV1GS4y1a7Rv/
题目链接
https://pintia.cn/problem-sets/994805046380707840/problems/994805065406070784
思路
由于给出了中根遍历以及先根遍历,我们先通过先根遍历定位到树的根节点,然后再通过中根遍历划分二叉树,然后再不断地往左往右递归处理左右子树,最后建立完这颗二叉树后,我们再在BFS
的时候优先把右子树放入队列,这样就能达到镜像反转的层序遍历,详情请看代码
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
#define INF 0x3f3f3f3f
const int N = 1e2+10;
int in[N],pre[N],n;
struct Node{
int l,r;
}Tree[N];
int build(int l1,int r1,int l2,int r2){//l1-r1中序遍历,l2-r2先序遍历
if(l1 > r1 || l2 > r2) return 0;
int p = l1;
while(in[p] != pre[l2]) p++;
int len = p - l1;
int rt = pre[l2];
Tree[rt].l = build(l1,p-1,l2+1,l2 + len);
Tree[rt].r = build(p+1,r1,l2+len+1,r2);
return rt;
}
void bfs(int s){
queue<int> que;
que.push(s);
int cnt = 0;
while(!que.empty()){
int rt = que.front();
que.pop();
cout<<rt<<" \n"[++cnt==n];
int l = Tree[rt].l,r = Tree[rt].r;
if(r) que.push(r);
if(l) que.push(l);
}
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
for(int i = 1;i <= n; ++i) cin>>in[i];
for(int i = 1;i <= n; ++i) cin>>pre[i];
build(1,n,1,n);
bfs(pre[1]);
return 0;
}