Files
python/TangDou/LuoGuBook/P1827.cpp

43 lines
1.6 KiB
C++
Raw Normal View History

2025-08-30 18:35:01 +08:00
#include <bits/stdc++.h>
using namespace std;
string pre_str; //前序
string in_str; //中序
//前序的第一个是根,后序是最后输出树的根 那就找一次输出一次,然后继续找出左树和右树,直到空树时停止。
/**
* 功能:对二叉树进行后序遍历.根据四个参数,(1)确定子树的根,(2)确定左右子树的大小范围,(3)按后序进行输出递归
* @param l1 前序遍历的起点
* @param r1 前序遍历的终点
* @param l2 中序遍历的起点
* @param r2 中序遍历的终点
*/
void dfs(int l1, int r1, int l2, int r2) {
if (l1 > r1 || l2 > r2) return;//规定边界条件
int i = in_str.find(pre_str[l1]); //利用根左右的特性来在中序队列中查找
int cnt = i - l2;//左子树的节点个数
//前序:l1是根,左子树是从l1+1开始,到l1+cnt结束
//中序:l2开始,到i-1结束
dfs(l1 + 1, l1 + cnt, l2, i - 1); //递归左子树
dfs(l1 + cnt + 1, r1, i + 1, r2); //递归右子树
cout << pre_str[l1]; //输出根结点
}
/**
ABEDFCHG
CBADEFGH
参考结果:AEFDBHGC
*/
int main() {
//输入中序遍历,前序遍历字符串
cin >> in_str >> pre_str;
int right = in_str.size() - 1; //right索引:因为是0开始,所以要-1
//递归构建还原二叉树
//本题,并没有真正的进行构建二叉树,只是根据二叉树的特点,不断查找过程中,输出后序遍历的字符串
dfs(0, right, 0, right);//每个字符串有两个指针指向头和尾
return 0;
}