九度OJ

来源:互联网 发布:php命名空间的作用 编辑:程序博客网 时间:2024/05/30 23:03

题目描述:

二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。

输入:

两个字符串,其长度n均小于等于26
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:ABC....最多26个结点。

输出:

输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。

样例输入:

ABCBACFDXEAGXDEFAG

样例输出:

BCAXEDGAF

参考代码:

//使用数组 #include<cstdio>#include<cstring>const int maxn=30;char s1[maxn],s2[maxn],s3[maxn];int lch[maxn],rch[maxn];int build(int L1,int R1,int L2,int R2){if(L1>R1) return 0;int root=s1[L1]-'A'+1;int p=L2;while(s2[p]-'A'+1!=root)p++;//在中序遍历中寻找根的位置int cnt=p-L2;lch[root]=build(L1+1,L1+cnt,L2,p-1);rch[root]=build(L1+cnt+1,R1,p+1,R2);return root;}int cnt;void postOrder(int u){if(lch[u])postOrder(lch[u]);if(rch[u])postOrder(rch[u]);s3[cnt++]=u+'A'-1;}int main(){while(scanf("%s%s",s1,s2)==2){int len=strlen(s1);build(0,len-1,0,len-1);cnt=0;postOrder(s1[0]-'A'+1);s3[cnt]='\0';printf("%s\n",s3);}return 0;}

//使用结构体 #include<cstdio>#include<cstring>const int maxn=30;char s1[maxn],s2[maxn],s3[maxn];struct Node{char c;Node *left;Node *right;Node():c(0),left(NULL),right(NULL){}};Node* build(int L1,int R1,int L2,int R2){if(L1>R1) return 0;Node *root=new Node();root->c=s1[L1];int p=L2;while(s2[p]!=root->c)p++;//在中序遍历中寻找根的位置int cnt=p-L2;  root->left=build(L1+1,L1+cnt,L2,p-1);root->right=build(L1+cnt+1,R1,p+1,R2);return root;}int cnt;void postOrder(Node *u){if(u->left)postOrder(u->left);if(u->right)postOrder(u->right);s3[cnt++]=u->c;}int main(){while(scanf("%s%s",s1,s2)==2){int len=strlen(s1);Node *root=build(0,len-1,0,len-1);cnt=0;postOrder(root);s3[cnt]='\0';printf("%s\n",s3);}return 0;}
原创粉丝点击