4512: 【例】【入门】根据前序中序求后序(2184)

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:6 解决:6

题目描述

给定一棵二叉树的前序遍历和中序遍历,求其后序遍历。

输入

读入 lns="http://www.w3.org/1998/Math/MathML">2 个两个字符串,每个一行,长度均小于等于 lns="http://www.w3.org/1998/Math/MathML">26

第一行为前序遍历,第二行为中序遍历。

二叉树中的结点名称以大写字母表示: lns="http://www.w3.org/1998/Math/MathML">ABC... 。

输出

输出一行,为后序遍历的字符串。

样例输入 复制

ABCDEFGH
CBEDAFHG

样例输出 复制

CEDBHGFA

提示

#include<bits/stdc++.h>
using namespace std;
string s1,s2;
void dfs(int l1,int r1,int l2,int r2) {
	int mid=s2.find(s1[l1]);
	if(mid>l2) dfs(l1+1,l1+mid-l2,l2,mid-1);
	if(mid<r2) dfs(l1+mid-l2+1,r1,mid+1,r2);
	cout<<s1[l1];
}
int main(){
    cin>>s1>>s2;
    dfs(0,s1.size()-1,0,s2.size()-1);
	return 0;
}