已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
输出
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linux xnuli
#include<stdio.h> #include<stdlib.h> #include<string.h> #define N 1000 struct node { char data; struct node *left; struct node *right; };struct node *make(char *a,char *b,int n){ struct node *now; char *p; int k = 0; if(n<=0) { return NULL; } now=(struct node*)malloc(sizeof(struct node)); (*now).data=*a; for(p=b;p<b+n;p++) { if(*p==*a) break; } k = p - b; (*now).left=make(a+1,b,k); (*now).right=make(a+1+k,p+1,n-k-1); return now; } void cengci(struct node *r) { int i=0,j=1; struct node *t[103]; t[0]=r; while(i < j)//队列不为空时 { if(t[i]!=NULL)// i 结点不为空时 { printf("%c",t[i]->data);//访问该节点 t[j++]=t[i]->left; //左分支进队列 t[j++]=t[i++]->right; //右分支进队列 } else i++; } } /*void cengci(struct node *r) { struct node *p; struct node *qu[N];//定义环形队列,存放结点指针 int head,wei;//定义队头,队尾指针 head= wei =-1;//队列初始化为空 wei ++; qu[wei ]=r;//根节点指针进入队列 while(head != wei )//队列不为空时 { head = (head+1)%N; p=qu[head]; //队头元素出列 printf("%c",p->data);//访问结点 if(p->left != NULL) { wei = (wei + 1) % N; //有左孩子时将其进队 qu[wei] = p->left; } if(p->right!=NULL) { wei=(wei + 1)%N;//有右孩子时将其进队 qu[wei]=p->right; } }}*/void lastord(struct node *t){ if(t==NULL) return ; lastord(t->left); lastord(t->right); printf("%c",t->data); }int main() { int T; struct node *tree; char a[100],b[100]; while(~scanf("%d",&T)) { while(T--) { scanf("%s",a); scanf("%s",b); int n=strlen(a); tree=make(a,b,n); lastord(tree); printf("\n"); cengci(tree); printf("\n"); } } return 0; }