根据一棵二叉树的中序,后序遍历的结果,可以唯一的确定一棵二叉树,这里附上代码实现从中序,后序遍历的序列转换成广度优先搜索遍历的序列(这里默认二叉树结点数目小于10000)
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<stack>
using namespace std;
const int maxn = 10010;
struct node
{
int lef, rig;
int info;
}tre[maxn];
int in[maxn], post[maxn], mp[maxn];
int root, cnt, n;
queue<int>q;
int build(int l, int r, int mid) {
if (l > r)return -1;
else if (l == r) {
tre[++cnt].info = post[mid];
tre[cnt].lef = -1;
tre[cnt].rig = -1;
return cnt;
}
int tmp = mp[post[mid]], t;
tre[++cnt].info = post[mid]; t = cnt;
tre[t].lef = build(l, tmp - 1, mid - r + tmp - 1);
tre[t].rig = build(tmp + 1, r, mid - 1);
return t;
}
void print() {
int tmp;
q.push(root);
while (!q.empty()) {
tmp = q.front();
q.pop();
printf("%d ", tre[tmp].info);
if (tre[tmp].lef != -1)
q.push(tre[tmp].lef);
if (tre[tmp].rig != -1)
q.push(tre[tmp].rig);
}
printf("\n");
}
int main()
{
int i, j;
char ch;
while (~scanf_s("%d%c", &in[1], &ch, 1)) {
n = 1; cnt = 0;
while (ch != '\n') {
scanf_s("%d%c", &in[++n], &ch, 1);
}
for (i = 1; i <= n; ++i) {
mp[in[i]] = i;
scanf_s("%d", &post[i]);
}
root = build(1, n, n);
print();
}
return 0;
}
/*
3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255
*/
测试样例:
3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255
测试结果:
4 2 7 3 1 5 6
5 7 12 11 16 18 8 3
255