poj 2255 Tree Recovery

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 4024 Accepted: 2698

本题与杭电acm上的1710几乎上相同,而且比杭电上的更容易些,所以在这里就不罗嗦了,如果有兴趣可以看我的另一篇随笔,hdu 1710  Binary Tree Traversals

代码:

 

  
    
1 #include < stdio.h >
2 #include < stdlib.h >
3 #include < string .h >
4   int n; char pre[ 30 ], in [ 30 ];
5 typedef struct node
6 {
7 char data;
8 int index;
9 struct node * Lchild, * Rchild;
10 }bitree, * Tree;
11   void dfs(Tree & root, int index)
12 {
13 if (root == NULL)
14 {
15 root = (Tree)malloc( sizeof (bitree));
16 root -> data = in [index];
17 root -> index = index;
18 root -> Lchild = NULL;
19 root -> Rchild = NULL;
20 return ;
21 }
22 else
23 {
24 if (index < root -> index)
25 dfs(root -> Lchild,index);
26 else
27 dfs(root -> Rchild,index);
28 }
29 }
30   void createbitree(Tree & root)
31 {
32 int i,j,index;
33 root = (Tree)malloc( sizeof (bitree));
34 for (i = 0 ;i < n;i ++ )
35 if ( in [i] == pre[ 0 ])
36 {
37 root -> data = pre[ 0 ];
38 root -> index = i;
39 root -> Lchild = NULL;
40 root -> Rchild = NULL;
41 break ;
42 }
43 index = i;
44 for (i = 1 ;i < n;i ++ )
45 for (j = 0 ;j < n;j ++ )
46 if ( in [j] == pre[i])
47 {
48 if (j < index)
49 dfs(root -> Lchild,j);
50 else
51 dfs(root -> Rchild,j);
52 break ;
53 }
54 }
55   void post(Tree root)
56 {
57 if (root == NULL)
58 return ;
59 post(root -> Lchild);
60 post(root -> Rchild);
61 printf( " %c " ,root -> data);
62 }
63   int main()
64 {
65 int i;
66 while (scanf( " %s%s " ,pre, in ) != EOF)
67 {
68 Tree root;
69 n = strlen(pre);
70 createbitree(root);
71 post(root);
72 printf( " \n " );
73 }
74 return 0 ;
75 }
76

 

 

你可能感兴趣的:(tree)