根据后序中序重构二叉树,并输出层次遍历模板
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 }
标签:重构,lb,la,int,中序,二叉树,now,ra 来源: https://www.cnblogs.com/-ytz/p/15911983.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。