L2-011. 玩转二叉树

参考博客

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <vector>
 6 #include <queue>
 7 #include <set>
 8 #include <map>
 9 #include <string>
10 #include <cmath>
11 #include <cstdlib>
12 #include <ctime>
13 #include <stack>
14 using namespace std;
15 const int maxn=50;
16 int mid[maxn],fr[maxn];
17 struct node{
18     int l,r;
19 }a[maxn];
20 
21 int build(int la,int ra,int lb,int rb)//la,ra表示中序遍历 lb,rb表示前序遍历
22 {
23     if(la>ra)
24         return 0;
25     int rt=fr[lb],p1,p2;
26     p1=la;
27     while(mid[p1]!=rt)    p1++;//在前序遍历中找到根节点
28     p2=p1-la;
29     a[rt].l=build(la,p1-1,lb+1,lb+p2);
30     a[rt].r=build(p1+1,ra,lb+p2+1,rb);
31     return rt;
32 }
33 void bfs(int x)//层序遍历
34 {
35     queue<int>q;
36     vector<int>v;
37     q.push(x);
38     while(!q.empty())
39     {
40         int w=q.front();
41         q.pop();
42         if(w==0)
43             break;
44         v.push_back(w);
45         if(a[w].r!=0)
46             q.push(a[w].r);
47         if(a[w].l!=0)
48             q.push(a[w].l);
49 
50     }
51     int len=v.size();
52     for(int i=0;i<len;i++)
53         printf("%d%c",v[i],i==len-1?'\n':' ');
54     return;
55 }
56 int main()
57 {
58     
59     int n,i,j;
60     cin>>n;
61     for(i=0;i<n;i++) scanf("%d",&mid[i]);
62     for(i=0;i<n;i++) scanf("%d",&fr[i]);
63     build(0,n-1,0,n-1);
64     int root=fr[0];
65     bfs(root);
66     return 0;
67 }