输入:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出:
4 1 6 3 5 7 2
思路:先把树建出来,再进行BFS
代码:
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 35;
int hx[N], zx[N], n;
vector<int> v[N];
void find(int zl, int zr, int hl, int hr, int f){ //建树
if(zl > zr || hl > hr) return;
v[f].push_back(hx[hr]); //存入子节点
int j = 1;
while(hx[hr] != zx[j]) j++; //在中序数组中找后序的点
find(zl, j - 1, hl, hl + j - zl - 1, hx[hr]); //找左子树
find(j + 1, zr, hl + j - zl, hr - 1, hx[hr]); //找右子树
}
void bfs(){ //层序遍历
queue<int> q;
q.push(hx[n]);
while(!q.empty()){
int p = q.front(); q.pop();
printf("%lld ", p);
for(int i = 0; i < v[p].size(); i++){
q.push(v[p][i]);
}
}
}
int32_t main(){
int tt = 1;
// cin >> tt;
while(tt--){
cin >> n;
for(int i = 1; i <= n; i++) cin >> hx[i];
for(int i = 1; i <= n; i++) cin >> zx[i];
find(1, n, 1, n, 0);
bfs();
}
}

386

被折叠的 条评论
为什么被折叠?



