九度OJ(1078)

来源:互联网 发布:软件著作权资助 编辑:程序博客网 时间:2024/06/16 18:20

二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
输入:
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C….最多26个结点。
输出:
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
样例输入:
ABC
BAC
FDXEAG
XDEFAG
样例输出:
BCA
XEDGAF

#include<iostream>#include<cstring>using namespace std;struct node{    node *right;    node *left;    char c;}tree[50];int l;node *creat(){    tree[l].left=tree[l].right=NULL;    return &tree[l];}string a,b;node *build(int s1,int e1,int s2,int e2){    node* root=creat();    l++;    root->c=a[s1];    int idx;    idx=b.find(root->c);    if(idx!=s2)    {        root->left=build(s1+1,s1+idx-s2,s2,idx-1);    }    if(idx!=e2)    {        root->right=build(s1+idx-s2+1,e1,idx+1,e2);    }    return root;}void postorder(node * t){    if(t->left!=NULL)    {        postorder(t->left);    }    if(t->right!=NULL)    {        postorder(t->right);    }    cout<<t->c;}int main(){    while(cin>>a)    {        cin>>b;        l=0;// 初始化静态内存空间中已经使用的节点个数;        int a1=a.size();        int b1=b.length();        node *t=build(0,a1-1,0,b1-1);        postorder(t);        cout<<endl;    }    return 0;}
0 0