版权声明:本文为博主原创文章,未经博主允许不得转载,不得用于商业用途。 https://blog.csdn.net/WDAJSNHC/article/details/82346231
codeup21193 求后续遍历
时空限制 1000ms/128MB
题目描述
输入一棵二叉树的先序和中序遍历序列,输出其后序遍历序列。
输入
输入共两行,第一行一个字符串,表示树的先序遍历,第二行一个字符串,表示树的中序遍历。树的结点一律用小写字母表示。
输出
输出仅一行,表示树的后序遍历序列。
样例输入
abdec dbeac
样例输出
debca
代码
#include<iostream>
#include<string>
using namespace std;
struct node{
char data;
node *lch,*rch;
};
void create(node *&root,string s1,string s2){
if (s1=="") { root=NULL; return; }
root = new node;
root->data = s1[0];
int len=s1.size(),p=s2.find(s1[0]);
create(root->lch,s1.substr(1,p),s2.substr(0,p));
create(root->rch,s1.substr(p+1,len-p-1),s2.substr(p+1,len-p-1));
}
void lastord(node *root){
if (root){
lastord(root->lch);
lastord(root->rch);
cout<<root->data;
}
}
int main(){
string s1,s2;
cin>>s1>>s2;
node *root(NULL);
create(root,s1,s2);
lastord(root);
cout<<endl;
return 0;
}