题目链接
输入样例:
8
6 8 7 4 5 1 3 2
8 5 4 7 6 3 2 1
输出样例:
R: 1 2 3 4 5
L: 1 6 7 8 5
答案
#include <iostream>
#include <algorithm>
#include<bits/stdc++.h>
#define ll long long
#define mem(a,b) memset(a,b,sizeof a)
#define ull unsigned long long
#define INF 0x3f3f3f3f3f3f3f3f
#define inf 0x3f3f3f3f
#define rep(i,a,b) for(auto i=a;i<=b;++i)
#define bep(i,a,b) for(auto i=a;i>=b;--i)
#define lowbit(x) x&(-x)
#define PII pair<int,int>
#define PLL pair<ll,ll>
#define PI acos(-1)
#define pb push_back
#define x first
#define y second
const double eps = 1e-6;
const int mod = 998244353;
const int MOD = 1e9 + 7;
const int N = 2e5 + 10;
const int M = 111;
int dx[]={-1, 0, 1, 0};
int dy[]={0, 1, 0, -1};
using namespace std;
struct tree {
int data;
tree *l, *r;
};
int pre[55], mid[55], post[55];
vector<int> BFSR(tree *root) {
if(root==NULL) return vector<int>{};
vector<int>ans;
queue<tree *> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
ans.push_back(q.front()->data);
while (size--)
{
tree *temp = q.front();
q.pop();
if (temp->r)
q.push(temp->r);
if (temp->l) q.push(temp->l);
}
}
return ans;
}
vector<int> BFSL(tree *root) {
if (root == NULL) return vector<int>{};
vector<int> ans;
queue<tree *> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
ans.push_back(q.front()->data);
while (size--) {
tree *temp = q.front();
q.pop();
if (temp->l) q.push(temp->l);
if (temp->r) q.push(temp->r);
}
}
return ans;
}
tree *buildtree(int len, int *post, int *mid) {
int i;
tree *root;
if (!len)
root = NULL;
else {
root = new tree;
root->data = post[len - 1];
for (i = 0; i < len; i++) {
if (mid[i] == post[len - 1]) {
break;
}
}
root->l = buildtree(i, post, mid);
root->r = buildtree(len - i - 1, post + i, mid + i + 1);
}
return root;
}
void solve(){
int n;
cin>>n;
for(int i=0;i<n;i++) cin>>mid[i];
for(int i=0;i<n;i++) cin>>post[i];
tree *root=new tree;
root=buildtree(n,post,mid);
cout<<"R:";
vector<int>ans=BFSR(root);
for(int i=0;i<ans.size();i++) cout<<" "<<ans[i];
cout<<endl;
vector<int> vp = BFSL(root);
cout << "L:";
for (int i = 0; i < vp.size(); i++) cout << " " << vp[i];
cout << endl;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}