Title Link: https://www.patest.cn/contests/gplt/L2-006
Thinking analysis: After the order can know the root, and then in the middle sequence to find the root, and can determine the left and right sub-tree, and then recursively to the left and the sub-tree decomposition, you can restore the two-fork tree. Finally, the built-up tree BFS can be written hierarchically traversed.
The AC code is as follows:
#include <iostream> #include <vector> #include <queue> #include <cstring> #include <cstdio
> Using namespace std;
const int maxn=3005;
int TREE[MAXN];
void build (int rt,vector<int>a,vector<int>b)//Recursive achievement {if (A.size () ==0) return;//recursive export int p=0;
for (int i=0;i<b.size (); i++)//Find root if (b[i]==a[a.size ()-1]) p=i;
vector<int>al,ar,bl,br; for (int i=0;i<p;i++) Al.push_back (A[i]);//Zuozi Order traversal sequence for (int i=p;i<a.size () -1;i++) Ar.push_back (A[i]);// The order of the right subtree is iterated over the sequence for (int i=0;i<p;i++) Bl.push_back (B[i]);//Zuozi the middle sequence traversal sequence for (int i=p+1;i<b.size (); i++) Br.push_back (b [i]); The middle sequence traversal sequence of the right subtree tree[rt]=b[p];//Jiangen build (RT<<1,AL,BL);//recursive build left subtree build (RT<<1|1,AR,BR);//recursive right subtree} void BF
S ()//with BFS hierarchy traversal {queue<int>q;
int root=1;
Q.push (root);
int f=0;
while (Q.size ()) {if (f++) cout<< "";
Root=q.front ();
cout<<tree[root];
Q.pop (); if (tree[Root<<1]!=-1] Q.push (root<<1);
if (tree[root<<1|1]!=-1) Q.push (root<<1|1);
} cout<<endl;
} int main () {//freopen ("In.txt", "R", stdin);
int n,x;
while (cin>>n) {memset (tree,-1,sizeof (tree));
vector<int>a,b;
for (int i=0;i<n;i++) cin>>x,a.push_back (x);
for (int i=0;i<n;i++) cin>>x,b.push_back (x);
Build (1,A,B);
BFS ();
} return 0;
}