POJ 2255 二叉树重构

传送门http://poj.org/problem?id=2255

要点:先序第一个是根节点,第二个是左子树的根;根据先序的信息,在中序中找到根节点,左边部分为左子树,右边为右子树。以上对每个子树也成立,直到找到叶节点,递归实现即可。

代码附上:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int maxn = 10000;
char pre[maxn];                 //先序
char mid[maxn];                 //中序
char left_child[maxn];          //记录左右子
char right_child[maxn];
int p;                          //先序指针
void build_tree(int s, int e, int x)
{
	if(s == e) return ;
	for(int i = s; i <= e ; i ++)
	{
	    if(mid[i] == x)
	    {
		    if(i - 1 >= s)
		    {
	            left_child[x] = pre[++p];
	            build_tree(s, i - 1, pre[p]);
		    }
		    if(i + 1 <= e)
		    {
	            right_child[x] = pre[++p];
	            build_tree(i + 1, e, pre[p]);
		    }
	        break;
	    }
	}
}

void postorder(int i)            
{
	int left = left_child[i];
	int right = right_child[i];
	if(left  != -1) postorder(left);
	if(right != -1) postorder(right);
	if(left == -1 && right == -1)
	{
		printf("%c",i);
		return;
	}
	printf("%c",i);
	return;
}
int main()
{
	while(scanf("%s %s",pre, mid) == 2)
	{
		p = 0;
		memset(left_child, -1, sizeof(left_child));
		memset(right_child, -1, sizeof(right_child));
		build_tree(0, strlen(pre) - 1, pre[0]);
		postorder(pre[0]);
		printf("\n");
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值