zoukankan      html  css  js  c++  java
  • 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]='';
            cout<<ans<<endl;
        }
    
        return 0;
    
    }
    

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

  • 相关阅读:
    Eclipse的下载与安装
    IntelliJ IDEA(2018)安装详解
    关于Idea中的web.xml 自动生成模板问题
    基于ssm框架的web.xml配置及解析
    Mybatis分页插件PageHelper的配置与基本使用
    基于maven的ssm框架pom.xml的基本配置及解析
    python去除字符串中的特殊字符(爬虫存储数据时会遇到不能作为文件名的字符串)
    快速指数算法
    伪随机序列
    django中Queryset的删除问题、分页问题
  • 原文地址:https://www.cnblogs.com/hellohacker/p/5822833.html
Copyright © 2011-2022 走看看