重构二叉树

根据后序中序重构二叉树,并输出层次遍历模板

 1 /**\
 2 input:
 3 7
 4 2 3 1 5 7 6 4
 5 1 2 3 4 5 6 7
 6 
 7 output:
 8 4 1 6 3 5 7 2
 9 \**/
10 #include <bits/stdc++.h>
11 
12 using namespace std;
13 
14 const int N = 40;
15 
16 int a[N], b[N];//后序 中序
17 
18 int n;
19 unordered_map<int, int > L, R;  // L[i]表示i的左儿子 R[i]表示i的右儿子
20 
21 //后序遍历区间[la,ra] 中序遍历区间[lb, rb]
22 int build(int la, int ra, int lb, int rb)
23 {
24     if(la > ra) return 0; //越界返回
25     int root = a[ra];     //根节点
26     int i;
27     for(i = lb; i <= rb && b[i] != root; i++) {}
28     if(i <= rb)
29     {
30         L[root] = build(la, ra - rb + i - 1, lb, i - 1);
31         R[root] = build(ra - rb + i, ra - 1, i + 1, rb);
32     }
33     return root;
34 }
35 void bfs(int root)
36 {
37     queue<int> q;
38     q.push(root);
39     int f = 0;
40     while(!q.empty())
41     {
42         int now = q.front();
43         q.pop();
44         f == 0 ? printf("%d", now) : printf(" %d", now);
45         f++;
46         if(L[now]) q.push(L[now]);
47         if(R[now]) q.push(R[now]);
48     }
49 }
50 
51 
52 signed main()
53 {
54     scanf("%d", &n);
55     for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
56     for(int i = 1; i <= n; ++i) scanf("%d", &b[i]);
57     int root = build(1, n, 1, n);
58     bfs(root);
59     return 0;
60 }

 

posted @ 2022-02-19 10:09  std&ice  阅读(71)  评论(0编辑  收藏  举报