1 # include <stdio.h>
2 # include <stdlib.h>
3 # include <string.h>
4 # define MAX 200
5 typedef struct node
6 {
7 char data;
8 struct node *l;
9 struct node *r;
10 }BT;
11 BT *rebuid(int n,char *pre,char *ord)
12 {//由前序树,中序树构造链式二叉树。
13 BT *T;
14 T=(BT *)malloc(sizeof(BT));
15 int x;
16 if(n <= 0)
17 return NULL;
18 x=strchr(ord,pre[0])-ord;
19 T->l=rebuid(x,pre+1,ord);
20 T->r=rebuid(n-x-1,pre+x+1,ord+x+1);
21 T->data=pre[0];
22 return T;
23 }
24 //后序遍历;
25 void postorder(struct node *T)
26 {
27 if(T)
28 {
29 postorder(T->l);
30 postorder(T->r);
31 printf("%c",T->data);
32 }
33 }
34 //层次遍历,队列实现。
35 void levelprint(struct node *root)
36 {
37 struct node *q[100], *p;
38 //*q[100]用于存储结构体类型的指针,p用于访问。
39 int front=0, rear=1;
40 //rear跟踪记录 子树的指针,front进行访问。
41 q[0]=root;
42 while(front < rear)
43 {//当还有子树节点没访问到,继续访问。
44 p=q[front++];//第一次指向根节点;第二次输出左子树。
45 printf("%c", p->data);
46 if(p->l != NULL)
47 q[rear++]=p->l;//如果存在左子树,左子树进队列;
48 if(p->r != NULL)
49 q[rear++] = p->r;//如果存在右子树,右子树进队列;
50 }//需要注意的是,front下标跟踪输出,rear下标记录子树。
51 //front总在前面,rear可能增加的很快。
52 }
53 int main()
54 {
55 BT *T;
56 char pre[MAX],ord[MAX];
57 int i,lenth,k;
58 scanf("%d",&k);
59 while(k--)
60 {
61 scanf("%s %s",pre,ord);
62 lenth=strlen(pre);
63 T=rebuid(lenth,pre,ord);
64 postorder(T);
65 printf("\n");
66 levelprint(T);
67 printf("\n");
68 }
69 return 0;
70 }