机试指南例3.4二叉树遍历

题目描述

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

输入描述:

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

输出描述:

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

输入

ABC
BAC
FDXEAG
XDEFAG

输出

BCA
XEDGAF
 
     
 1 #include<stdio.h>
 2 #include<string.h>
 3 char str1[30],str2[30];
 4 struct Node
 5 {
 6     Node *lchild;
 7     Node *rchild;
 8     char c;
 9 }Tree[50];
10 int loc;
11 Node *creat()
12 {
13     Tree[loc].lchild=Tree[loc].rchild=NULL;
14     return &Tree[loc++];
15 }
16 Node *build(int s1,int e1,int s2,int e2)
17 {
18     Node *ret=creat();
19     ret->c=str1[s1];
20     int rootIdx;
21     for(int i=s2;i<=e2;i++)
22     {
23         if(str2[i]==str1[s1])
24         {
25             rootIdx=i;
26             break;
27         }
28     }
29     if(rootIdx!=s2)
30     {
31         ret->lchild=build(s1+1,s1+(rootIdx-s2),s2,rootIdx-1);
32     }
33     if(rootIdx!=e2)
34     {
35         ret->rchild=build(s1+(rootIdx-s2)+1,e1,rootIdx+1,e2);
36     }
37     return ret;
38 }
39 void postOrder(Node *T)
40 {
41     if(T->lchild!=NULL) postOrder(T->lchild);
42     if(T->rchild!=NULL) postOrder(T->rchild);
43     printf("%c",T->c);
44 }
45 int main()
46 {
47     while(scanf("%s",str1)!=EOF)
48     {
49         scanf("%s",str2);
50         loc=0;
51         int L1=strlen(str1);
52         int L2=strlen(str2);
53         Node *T=build(0,L1-1,0,L2-1);
54         postOrder(T);
55         printf("\n");
56     }
57     return 0;
58 }
View Code

猜你喜欢

转载自www.cnblogs.com/qing123tian/p/11115747.html