L2-006. 树的遍历

参考博客

 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],be[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=be[rb],p1,p2;
26     p1=la;
27     while(mid[p1]!=rt)    p1++;//在中序遍历中找到根节点
28     p2=p1-la;
29     a[rt].l=build(la,p1-1,lb,lb+p2-1);
30     a[rt].r=build(p1+1,ra,lb+p2,rb-1);
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].l!=0)
46             q.push(a[w].l);
47         if(a[w].r!=0)
48             q.push(a[w].r);
49     }
50     int len=v.size();
51     for(int i=0;i<len;i++)
52         printf("%d%c",v[i],i==len-1?'\n':' ');
53     return;
54 }
55 int main()
56 {
57     //freopen("in.txt","r",stdin);
58     //freopen("out.txt","w",stdout);
59     int n,i,j;
60     cin>>n;
61     for(i=0;i<n;i++) scanf("%d",&be[i]);
62     for(i=0;i<n;i++) scanf("%d",&mid[i]);
63     build(0,n-1,0,n-1);
64     int root=be[n-1];
65     bfs(root);
66     return 0;
67 }