天梯赛 L2-011 玩转二叉树
和上面一道树的题思路一样,只需要换一下递归的顺序即可。
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
// #define int long long
typedef long long ll;
const int N = 50;
int n;
int a[N],b[N];
struct nod{
int value;
nod* l = NULL;
nod* r = NULL;
};
nod* build(int al,int ar,int bl,int br){
if(al > ar) return NULL;
nod* root = (nod*)malloc(sizeof(nod));
root->value = a[al];
int x = a[al];
int p = bl;
while(b[p] != x){
p++;
}
int len = p - bl;
root->l = build(al+1,al+len,bl,p-1);
root->r = build(al+len+1,ar,p+1,br);
return root;
}
void bfs(nod* x){
queue<nod> q;
q.push(*x);
while(!q.empty()){
nod tmp = q.front();
q.pop();
if(tmp.value != x->value) cout<<" ";
cout<<tmp.value;
if(tmp.r != NULL) q.push(*(tmp.r));
if(tmp.l != NULL) q.push(*(tmp.l));
}
}
void solve() {
cin>>n;
for(int i = 1 ; i <= n ; i++){
cin>>b[i];
}
for(int i = 1 ; i <= n ; i++){
cin>>a[i];
}
nod* head = build(1,n,1,n);
bfs(head); //输出
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int tt = 1;
// cin >> tt;
while (tt--) {
solve();
}
return 0;
}