一般二叉树遍历序列转换

根据一棵二叉树的中序,后序遍历的结果,可以唯一的确定一棵二叉树,这里附上代码实现从中序,后序遍历的序列转换成广度优先搜索遍历的序列(这里默认二叉树结点数目小于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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值