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

  • 相关阅读:
    08测试环境配置_数据库配置
    11等价类
    15状态迁移
    12边界值分析法
    10用例格式
    python的转义字符和原字符
    13数据分析法
    14正交试验
    python软件安装
    cookie的secure属性
  • 原文地址:https://www.cnblogs.com/hellohacker/p/5822833.html
Copyright © 2011-2022 走看看