L2-006 树的遍历
先建树,然后遍历数组。
这种方式比较消耗空间,适用于数据量小的情况,如果形成一条链,那将是致命的这个空间。
方法一,数组二叉树
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int in[N], post[N];
vector<int> tree(N,-1);
void build(int root, int start, int ed, int idx) {
if (start > ed) return;
int i;
for (i = start; i <= ed; i++) {
if (in[i] == post[root]) {
break;
}
}
tree[idx] = post[root];
build(root - ed + i - 1, start, i - 1, 2 * idx);//左
build(root - 1, i + 1, ed, 2 * idx + 1);//右
}
int main() {
int ssize;
cin >> ssize;
for (int i = 0; i < ssize; i++) {
cin >> post[i];
}
for (int i = 0; i < ssize; i++) {
cin >> in[i];
}
build(ssize - 1, 0, ssize - 1, 1);
int flag = 0;
for (int i = 1; i < tree.size(); i++) {
if (tree[i] != -1) {
if(flag) cout << " ";
cout << tree[i];
flag++;
}
}
return 0;
}
方法二,正常建树+BFS
#include <bits/stdc++.h>
using namespace std;
const int N = 40;
int in[N], post[N];
int L[N], R[N];
int build(int pl,int pr, int il, int ir) {
if (pl > pr) return -1;
int root = post[pr];
int i;
for (i = il; i <= ir; i++) {
if (in[i] == root) {
break;
}
}
int Lsize = i - il;
int Rsize = ir - i;
L[root] = build(pl,pl+Lsize-1,il,i-1);
R[root] = build(pr-Rsize,pr-1,i+1,ir);
return root;
}
void BFS(int root) {
queue<int> que;
que.push(root);
int flag = 0;
while (!que.empty()) {
int x = que.front();
que.pop();
if (flag) cout << " ";
cout << x;
flag++;
if (L[x] != -1) que.push(L[x]);
if (R[x] != -1) que.push(R[x]);
}
}
int main() {
int ssize;
cin >> ssize;
for (int i = 0; i < ssize; i++) {//后序
cin >> post[i];
}
for (int i = 0; i < ssize; i++) {//中序
cin >> in[i];
}
int root = build(0,ssize-1,0,ssize-1);
BFS(root);
return 0;
}