Tree Recovery,UVa536

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;

const int MAXN = 100+10;
char pre_order[MAXN], in_order[MAXN];
char lch[MAXN], rch[MAXN];

char build_tree(int L1, int R1, int L2, int R2);
void post_order(char a);

int main()
{
	while(cin>>pre_order){
		cin>>in_order;
		int n = strlen(pre_order);
		build_tree(0,n-1,0,n-1);
		post_order(pre_order[0]);
		cout<<endl;
	}
	return 0;
}
//把pre_order[L1.....R1]和post_order[L2..R2]建成一棵树返回树根 
char build_tree(int L1, int R1, int L2, int R2)
{
	if(L2>R2) return '0';
	char root;
	root = pre_order[L1];
	int p = L2;
	while(in_order[p] != root ) p++;
	int cnt = p-L2;
	lch[root-'A'] = build_tree(L1+1,L1+cnt,L2,p-1);
	rch[root-'A'] = build_tree(L1+cnt+1, R1, p+1, R2);
	return root;
}

void post_order(char a){
	if(lch[a-'A'] != '0') post_order(lch[a-'A']);
	if(rch[a-'A'] != '0') post_order(rch[a-'A']);
	cout<<a;
	return; 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值