P1030
树形结构里的经典题,也是必备的入门题
首先,放上一个结论,如若想唯一确定一个树,必须得至少已知它的中序遍历,否则不管你哪怕知道前序、后序、层序遍历,也无法唯一确定一个树。
一、已知先序中序求后序
第一步,先序遍历第一个位置肯定是根节点,然后在中序遍历中确定该根结点的位置
第二步,确定好位置后,即可分别对左子树和右子树进行递归
具体左子树和右子树的一个范围下标在图中已经很明显了,就不再做多余解释。
直接干代码:
void post_order(int x, int y, int p, int q) { //x~y为前序遍历 p~q为中序遍历
if (x > y || p > q) return;//规定边界条件
else {
int root_pos = s2.find(s1[x]); //利用根左右的特性来在中序队列中查找
post_order(x + 1, x + root_pos - p, p, root_pos - 1); //递归左子树
post_order(x + root_pos - p + 1, y, root_pos + 1, q); //递归右子树
cout << s1[x];
}
}
二、已知后序中序求先序
第一步,后序遍历最后一个位置肯定是根节点,然后在中序遍历中确定该根结点的位置
第二步,确定好位置后,即可分别对左子树和右子树进行递归
干代码:
void pre_order(int x, int y, int p, int q) { //x~y为中序遍历 p~q为后序遍历
if (x > y || p > q) return;//规定边界条件
else {
int root_pos = s1.find(s2[q]); //利用根左右的特性来在中序队列中查找
cout << s2[q];
pre_order(x, root_pos - 1, p, p + root_pos - x - 1); //递归左子树
pre_order(root_pos + 1, y, p + root_pos - x, q - 1); //递归右子树
}
}
最后干上完整代码:
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <stack>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
#include <fstream>
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define LNF = 0x3f3f3f3f3f3f3f3f;
using namespace std;
const int maxn = 100002;
string s1, s2;
void post_order(int x, int y, int p, int q) { //x~y为前序遍历 p~q为中序遍历
if (x > y || p > q) return;//规定边界条件
else {
int root_pos = s2.find(s1[x]); //利用根左右的特性来在中序队列中查找
post_order(x + 1, x + root_pos - p, p, root_pos - 1); //递归左子树
post_order(x + root_pos - p + 1, y, root_pos + 1, q); //递归右子树
cout << s1[x];
}
}
void pre_order(int x, int y, int p, int q) { //x~y为中序遍历 p~q为后序遍历
if (x > y || p > q) return;//规定边界条件
else {
int root_pos = s1.find(s2[q]); //利用根左右的特性来在中序队列中查找
cout << s2[q];
pre_order(x, root_pos - 1, p, p + root_pos - x - 1); //递归左子树
pre_order(root_pos + 1, y, p + root_pos - x, q - 1); //递归右子树
}
}
int main() {
//cin >> s2 >> s1; //把中前遍历当做字符串输入
//int len = s1.length() - 1;//因为是0开始,所以要减一
//post_order(0, len, 0, len);//递归求后序遍历
cin >> s1 >> s2; //把中后遍历当做字符串输入
int len = s1.length() - 1;//因为是0开始,所以要减一
pre_order(0, len, 0, len);//递归求前序遍历
return 0;
}