求后序遍历

求后序遍历

Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 3   Accepted Submission(s) : 2

Font: Times New Roman | Verdana | Georgia

Font Size:  

Problem Description

输入一棵二叉树的先序和中序遍历序列,输出其后序遍历序列。

Input

输入有多组数据,对于输入每组数据有两行,第一行一个字符串(字符串长度不超过30),表示树的先序遍历,第二行一个字符串,表示树的中序遍历。树的结点一律用小写字母表示。

Output

对于每组输入输出仅一行,表示树的后序遍历序列。

Sample Input

abdec
dbeac

Sample Output

debca

#include <iostream>
#include <string>
using namespace std;
int find1(string s1,char c)
{
    for(int i=0;i<s1.size();i++)
        if(c==s1[i])
            return i;
        return -1;
}
bool bianli(string &pre,string &mid)
{
    if(pre.size()==0)
        return false;
    if(pre.size()==1)
    {
        cout<<pre;
        return true;
    }
    int k=find1(mid,pre[0]);
    string newpre=pre.substr(1,k);
    string newmid=mid.substr(0,k);
    bianli(newpre,newmid);
    newpre=pre.substr(k+1,pre.size()-k-1);
    newmid=mid.substr(k+1,mid.size()-k-1);
    bianli(newpre,newmid);
    cout<<pre[0];
}
int main ()
{
    string pre,mid;
    while(cin>>pre>>mid)
    {
        bianli(pre,mid);
        cout<<endl;
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/u010760034/article/details/17011025