天天看點

UVa536_Tree Recovery

題目:點選打開連結

思路:根據先序周遊找到樹根,再在中序周遊中找到樹根,進而找到左右樹結點中序周遊,然後遞歸構造左右子樹。

#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<stack>
#include<vector>
#include<queue>
#include<cstring>
#include<sstream>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;

string pre_order, in_order;        //先序周遊、中序周遊
int lch[60], rch[60];              //左子樹、右子樹

int build(int L1, int R1, int L2, int R2){   //L1—R1為先序周遊,L2-R2為中序周遊
	if (L1 > R1) return 0;					//空樹
	int  root = pre_order[L1]-'A'+1;        //在先序周遊中找到樹根
	int p = L2;
	while (in_order[p]-'A'+1 != root) 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 bfs(int root){
	if (lch[root])	bfs(lch[root]);
	if (rch[root])	bfs(rch[root]);
	printf("%c", root+'A'-1);
}

int main(){
	//freopen("random_numbers.txt","r",stdin);
	while (cin >> pre_order >> in_order){
		int len = pre_order.length();
		build(0, len - 1, 0, len - 1);
		bfs(pre_order[0]-'A'+1);		
		printf("\n");
	}
	return 0;
}