注意:允许转载,但转载请注明作者和出处
最重要:queue和stack不支持遍历+创建树
AcWing 1497. 树的遍历
题目
解析
答案
#include <iostream>
#include <unordered_map>
#include <queue>
using namespace std;
const int N = 40;
unordered_map<int, int> l, r, pos;
int in[N], post[N];
int n;
int build(int il, int ir, int pl, int pr)
{
int root = post[pr];
int k = pos[root];
if (il < k)
l[root] = build(il, k - 1, pl, pl + k - 1 - il);
if (ir > k)
r[root] = build(k + 1, ir, pl + k - 1 - il + 1, pr - 1);
return root;
}
void bfs(int root)
{
// stack容器,queue容器不允许有遍历行为
// 若想遍历,则要不就直接在访问某个值的时候输出某个值,
// 要不就放在vector中
queue<int> q;
q.push(root);
while (q.size())
{
auto t = q.front();
cout << t << ' ';
q.pop();
if (l.count(t)) q.push(l[t]);
if (r.count(t)) q.push(r[t]);
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++) cin >> post[i];
for (int i = 0; i < n; i ++)
{
cin >> in[i];
pos[in[i]] = i;
}
int root = build(0, n - 1, 0, n - 1);
bfs(root);
return 0;
}