题目:点击打开链接
思路:根据先序遍历找到树根,再在中序遍历中找到树根,从而找到左右树结点中序遍历,然后递归构造左右子树。
#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;
}