[NOIP2001 普及组] 求先序排列(preorder)
题目描述
给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,且二叉树的节点个数 $ \le 8$)。
输入格式
共两行,均为大写字母组成的字符串,表示一棵二叉树的中序与后序排列。
输出格式
共一行一个字符串,表示一棵二叉树的先序。
样例 #1
样例输入 #1
BADC
BDCA样例输出 #1
ABCD提示
【题目来源】
NOIP 2001 普及组第三题
题解
首先,后序遍历的最后一个就是根(ABCD,则根为D)
求先序我们就不断找根
中序ACGDBHZKX,后序CDGAHXKZB,先找到根B,在中序遍历中找到B,可将中序遍历分成两个课子树ACGD和HZKX。后序遍历就是CDGA和HXKZ。问题就变成求中序遍历ACGD,后序遍历CDGA的树,和中序遍历HZKX,后序遍历HXKZ的树;
接着递归,按照之前的方法,找到子根A,再分为两棵子树,字根Z,再分为两棵子树。
一直递归下去,找到根就输出
c++
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define ull unsigned long long
#define endl '\n'
const int N = 1e5 + 5;
const int mod = 1e9 + 7;
const ll inf = 1e18;
int dir[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1}; // 上右下左
void search(string inorder, string postorder) {
if (inorder.size() > 0) {
cout << postorder[postorder.size() - 1];
int pos = inorder.find(postorder[postorder.size() - 1]); // 找中序遍历的根的位置
search(inorder.substr(0, pos), postorder.substr(0, pos)); // 递归左子树
search(inorder.substr(pos + 1), postorder.substr(pos, inorder.size() - pos - 1)); // 递归右子树(-1是因为下标从开始计算的)
}
}
void solve() {
string inorder, postorder;
cin >> inorder >> postorder;
search(inorder, postorder);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _ = 1;
//cin >> _;
while (_--) {
solve();
}
return 0;
}