3598. 二叉树遍历(给出前、中序,求后序)

题目https://www.acwing.com/problem/content/3601/

目录

 Answer(按子树前、中序序列 递归):

假定一棵二叉树的每个结点都用一个大写字母描述。

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

输入格式

输入包含多组测试数据。

每组数据占两行,每行包含一个大写字母构成的字符串,第一行表示二叉树的前序遍历,第二行表示二叉树的中序遍历

输出格式

每组数据输出一行,一个字符串,表示二叉树的后序遍历

数据范围

输入字符串的长度均不超过 26。

输入样例:

ABC
BAC
FDXEAG
XDEFAG

输出样例:

BCA
XEDGAF

 Answer(按子树前、中序序列 递归):

#include<bits/stdc++.h>
#define ll long long
using namespace std;
 /*
    1,  Core: 前序遍历的第一个点一定为结点,在中序遍历中找此结点的位置,
            左边为左子树,右边为右子树

    2,  递归函数参数:
           string pre:子树的前序遍历,
           string in :子树的中序遍历,   (注意不要把结点下放到子串的pre,in中)

    3,  C++ :
            str.find(X): 返回str中第一次出现X元素的位置(下表)
            str.substr(x,y): 截取子串, 从x位置开始,长度为y
            str.substr(x) : 截取子串, 从x位置到末尾

    4,  前中后 序遍历(访问结点,以结点为准):
               根 左 右
               左 根 右
               左 右 根
*/
void postorder(string pre,string in)
{
    if(!pre.size())
        return ;
    int mid=in.find(pre[0]);// mid:
    postorder(pre.substr(1,mid),in.substr(0,mid));
    postorder(pre.substr(mid+1),in.substr(mid+1));
    printf("%c",pre[0]);
}
int main()
{
    //freopen("input.txt","r",stdin);
   //string s="123456789";
    //cout<<s.substr(8);
    string s1,s2;
     while(cin>>s1>>s2)
     {
        postorder(s1,s2);
        cout<<endl;
     }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值