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表示函数返回字串的长度。

  • 相关阅读:
    web应用后台开发的故事
    XML的定义、用途、以及它的发展前景和存在的问题等等
    本学期(大三下学期)学习目标
    企业级应用与互联网应用的区别?
    新能源汽车无线充电管理网站4
    新能源汽车无线充电管理网站3
    新能源汽车无线充电管理网站2
    企业级应用与互联网应用的区别
    javaee 新学期新目标
    团队项目PCP--自我评价
  • 原文地址:https://www.cnblogs.com/hellohacker/p/5822833.html
Copyright © 2011-2022 走看看