L2-006 树的遍历
Posted alingmaomao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了L2-006 树的遍历相关的知识,希望对你有一定的参考价值。
#include<iostream> #include<queue> #include<vector> using namespace std; const int maxn = 100; int af[maxn], in[maxn], n; struct node{ int l, r; }tree[maxn]; int biuld(int al, int ar, int bl, int br){ if (al > ar)return 0; int root, p1, len; root = af[br]; for (p1 = al; p1 <= ar; ++p1)if (in[p1] == root)break; len = p1 - al; tree[root].l = biuld(al, p1 - 1, bl, bl + len-1); tree[root].r = biuld(p1 + 1, ar, bl + len, br - 1); return root; } void BFS(int x){ queue<int>q; vector<int>v; q.push(x); while (!q.empty()){ int root = q.front(); q.pop(); if (root == 0)break; v.push_back(root); if (tree[root].l)q.push(tree[root].l); if (tree[root].r)q.push(tree[root].r); } int len = v.size(); for (int i = 0; i < len; ++i) cout << v[i] << " "[i == len - 1]; } int main(){ cin >> n; for (int i = 0; i < n; ++i)cin >> af[i]; for (int i = 0; i < n; ++i)cin >> in[i]; int root = biuld(0, n - 1, 0, n - 1); BFS(root); }
以上是关于L2-006 树的遍历的主要内容,如果未能解决你的问题,请参考以下文章