蓝桥杯训练——[蓝桥杯][算法训练VIP]求先序排列

题目链接:https://www.dotcpp.com/oj/problem1648.html

题目描述

给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度< =8)。

输入

两行,每行一个字符串,分别表示中序和后序排列 

输出

一个字符串,表示所求先序排列 

样例输入

BADC 
BDCA 

样例输出

ABCD
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <cstdio>
#include <string>
#include <stack>
#include <set>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
using namespace std;
typedef long long ll;
string ans;
//dfs求中序遍历序列为a,后序遍历为b的先序序列
void dfs(string a,string b){
    if(a.length()==0)return ;
    ans.push_back(b[b.length()-1]);
    char c=b[b.length()-1];
    int mid=0;
    while(a[mid]!=c){
        mid++;
    }
    dfs(a.substr(0,mid),b.substr(0,mid));//左子树
    dfs(a.substr(mid+1,a.length()-mid-1),b.substr(mid,b.length()-mid-1));//右子树
    return ;
}
int main()
{
    IOS;
    string a,b;
    cin>>a>>b;
    dfs(a,b);
    cout<<ans<<endl;
    getchar();
    getchar();
    return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值