习题6_3 二叉树重建(Tree Recovery, ULM 1997, UVa536)

题目描述:

输入一棵树的先序遍历和中序遍历序列,输出后序遍历序列

AC代码:

#include
#include

const int MAX_N = 30;
char pre_order[MAX_N], in_order[MAX_N];
int lch[MAX_N], rch[MAX_N];
char root;

//根据前序 L1~R1, 中序 L2~R2构造二叉树 
int build(int L1, int R1, int L2, int R2) {
     
	if(L2 > R2) return -1;
	int root = pre_order[L1] - 'A';
	int p = L2; 
	while(in_order[p] != root + 'A') 
		p++;
	int cnt = p - L2;  //左子结点的个数 
	lch[root] = build(L1+1, L1+cnt, L2, L2+cnt-1);
	rch[root] = build(L1+cnt+1, R1, L2+cnt+1, R2);
	return root;
}

void PostOrder(int x) {
     
	if(x == -1) return;
	PostOrder(lch[x]);
	PostOrder(rch[x]);
	printf("%c", x+'A');
}

int main() {
     
	#ifdef LOCAL
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
	#endif
	while(scanf("%s%s", pre_order, in_order) == 2) {
     
		root = build(0, strlen(pre_order)-1, 0, strlen(in_order)-1);
		PostOrder(root);
		printf("\n");
	}
	return 0;
}

你可能感兴趣的:(算法竞赛,二叉树,算法,数据结构)