toj ~3988~递归二叉树三种遍历的转换

3988.    Password
Time Limit: 1.0 Seconds    Memory Limit: 65536K
Total Runs: 476    Accepted Runs: 200



Bob will get a bag as gift from Alice, but Alice don't wanna Bob get the bag without did anything, so she put the bag into a safe box... Alice will give two hints about password to Bob. One is the preorder traversal(root, left subtree, right subtree) of a binary tree, another is the inorder traversal(left subtree, root, right subtree) of the same tree. The password is the postorder traversal(left subtree, right subtree, root) of the tree.
For example:

The tree only has three nodes A, B and C.
Its preorder traversal is ABC, inorder traversal is BAC, and postorder traversal is BCA.

 

Input

There are several test cases in the input file, Each test case contains two line. Preorder traversal and Inorder traversal.(Each line's length won't longer than 26, and only contain upper letter)

Output

For each test case, output the password Bob need.

Sample Input

 

ABC
BAC

 

Sample Output

 

BCA

 



Source: TJU Team Selection 2013

#include<iostream>
#include<string>
#include<cstdio>
using namespace std;

char ans[30];  //保存后序遍历序列
int t=0;

void solve(string s1,string s2)
{

    if(s1.length()==0) return ;
    else if(s1.length()==1)
    {
        ans[t++]=s1[0];
        return ;
    }
    else {
        int tt=s2.find(s1[0]);
        solve(s1.substr(1,tt),s2.substr(0,tt));  //左子树的后序遍历
        solve(s1.substr(tt+1,s1.length()-tt-1),s2.substr(tt+1,s2.length()-tt-1));   //右子树的后序遍历
        ans[t++]=s1[0];
    }
}
int main()
{
    string stra,strb;
    while(cin>>stra>>strb)
    {
        int len=stra.length();
        t=0;
        solve(stra,strb);
        ans[len]='\0';
        cout<<ans<<endl;
    }

    return 0;

}

  length()函数是string类的成员函数,返回该对象字符串的长度,substr()函数是string类成员函数,函数返回值是该字符串的子串,原型是substr(int pos,int n);其中pos是子串开始时的下标,n表示函数返回字串的长度。

转载于:https://www.cnblogs.com/hellohacker/p/5822833.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值