二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
ABC
CBA
ABCDEFG
DCBAEFG
CBA
DCBGFEA
注释:纯纯将两个模板套在一起。
代码:
- #include
- using namespace std;
- typedef struct ww{
- char data;
- struct ww *lchild,*rchild;
- }*btree;
- btree pre_mid_createbtree(char *pre,char*mid,int len){//先序,中序还原二叉树
- if(len==0){
- return NULL;
- }
- char ch=pre[0];//先序中的第1个节点为根
- int index=0;
- while(mid[index]!=ch){//在中序中找到根的位置
- index++;
- }
- btree t=new ww;//创建根节点
- t->data=ch;
- t->lchild=pre_mid_createbtree(pre+1,mid,index);//创建左子树
- t->rchild=pre_mid_createbtree(pre+index+1,mid+index+1,len-index-1);//创建右子树
- return t;
- }
- void posorder(btree t){
- if(t){
- posorder(t->lchild);
- posorder(t->rchild);
- cout<
data; - }
- }
- char s1[100],s2[100];
- int main(){
- while(~scanf("%s",s1)){
- scanf("%s",s2);
- int n=strlen(s1);
- posorder(pre_mid_createbtree(s1,s2,n));
- cout<
- }
- }