题目描述
输入
输出
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linuxxnuli
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef char element; typedef struct BNode { element data; BNode *lchild,*rchild; }*BiTree; typedef struct QNode { BiTree data; QNode *next; }*queueptr; typedef struct { queueptr front; queueptr rear; }queue; char pre[54],ino[54]; /*void bian(BiTree &T,char pre[],char ino[],int ps,int is,int length)//注意用此函数建树会超时; { if(length==0) T=NULL; else { int k=0; int m=strlen(ino); for(k=0;k<m;k++) if(ino[k]==pre[ps]) break; T=new BNode; if(!T) exit(0); T->data=pre[ps]; if(k==is) T->lchild=NULL; else bian(T->lchild,pre,ino,ps+1,is,k-is); if(k==is+length-1) T->rchild=NULL; else bian(T->rchild,pre,ino,ps+k-is+1,k+1,length-(k-is)-1); } }*/ BiTree BinaryTree(char *pre,char *ino,int n)//已知前序和中序 { if(n==0) return 0;//递归结束条件 BiTree T=new BNode; if(!T) exit(0);//空间溢出; T->data=*pre;//前序序列的第一个元素即为根节点 int rootIndex=0; for(;rootIndex<n;rootIndex++)//找到根节点在中序序列中的位置,用以划分左右子树 if(ino[rootIndex]==*pre) break; T->lchild=BinaryTree(pre+1,ino,rootIndex);//对左子树重复上述操作 T->rchild=BinaryTree(pre+rootIndex+1,ino+rootIndex+1,n-(rootIndex+1));//对右子树重复上述操作 return T; //输出位置(求后序序列) } void postorder(BiTree &T)//树后序序列的输出 { if(T) { postorder(T->lchild); postorder(T->rchild); printf("%c",T->data); } } void initqueue(queue &Q)//队的初始化; { Q.front=Q.rear=(queueptr)malloc(sizeof(QNode)); if(!Q.front) exit(0);//空间溢出; Q.front->next=NULL; } void Enqueue(queue &Q,BiTree &e)//从队尾进队; { queueptr p; p=(queueptr)malloc(sizeof(QNode)); if(!p) exit(0); p->data=e; p->next=NULL; Q.rear->next=p; Q.rear=p; } element Dequeue(queue &Q,BiTree &e)//从队头出队; { queueptr p; if(Q.front==Q.rear) return 0; p=Q.front->next; e=p->data; Q.front->next=p->next; if(Q.rear==p) Q.rear=Q.front; free(p); return 1; } int Emptyqueue(queue &Q)//空队的判断; { if(Q.front==Q.rear) return 0; else return 1; } void traverse(BiTree &T)//对树每层的节点进行访问,层次遍历序列; { queue Q; initqueue(Q); if(T)//第一个非空根节点进队 Enqueue(Q,T); while(Emptyqueue(Q)) { Dequeue(Q,T); printf("%c",T->data); if(T->lchild) Enqueue(Q,T->lchild); if(T->rchild) Enqueue(Q,T->rchild); } } int main() { int n; scanf("%d",&n); while(n--) { BiTree T;//树的定义 scanf("%s\n%s",pre,ino); int m=strlen(ino); T=BinaryTree(pre,ino,m);//已知前中序列求后序列; postorder(T);//后序列的访问输出 printf("\n"); traverse(T);//层次序列的访问输出; printf("\n"); } }