UVA 536 Tree Recovery 建树+不建树

题意:

给出先序和中序,求后序。

思路:

①建树然后递归输出。

 1 //建树的
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<queue>
 5 #include<cstring>
 6 using namespace std;
 7 
 8 int n;
 9 char pre[1010],mid[1010];
10 int judge[1010];
11 struct node{
12     
13     char c;
14     node *left,*right;
15     node()
16     {
17         c='a';
18         left=right=NULL;
19     }
20 };
21 int cnt=0,counter;
22 node* build(node *root)
23 {
24     char c=pre[cnt++];//从a中取数 去b中查找
25     int i;
26     for( i=0;i<n;i++)
27     {
28         if(mid[i]==c)
29         break;
30     }
31     judge[i]=1;
32     root=new node();
33     root->c=c;
34     if(i>0&&i<n&&judge[i-1]!=1)//在b数组中,如果一个数左相邻的数被标记,则不能向左建树
35         root->left=build(root->left);
36     if(i>=0&&i<n-1&&judge[i+1]!=1)//同样,在b数组中,如果一个数右相邻的数被标记,则不能向右建树
37         root->right=build(root->right);
38     return root;    //左右都建完,返回根结点
39 }
40 
41 void postorder(node *root)
42 {
43     if(root->left)
44     postorder(root->left);
45     if(root->right)
46     postorder(root->right);
47     if(counter)
48     //printf(" ");
49     //counter++;
50     printf("%c",root->c);
51 }
52 
53 int main()
54 {
55     while(scanf("%s %s",pre,mid)==2)
56     {
57         //printf("%s %s\n",pre,mid);
58         counter = 0;
59         cnt = 0;
60         n=strlen(pre);
61         memset(judge,0,sizeof(judge));
62         
63         node *root = NULL;
64         root = build(root);
65         postorder(root);
66         printf("\n");
67     }
68     return 0;
69 }

 

②不建树直接输出。

 1 //不建树
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<queue>
 5 #include<cstring>
 6 using namespace std;
 7 
 8 int n;
 9 char pre[1010],mid[1010];
10 int cnt=0,counter;
11 void work(int left,int right)//左右端点
12 {
13     int i;
14     char c=pre[cnt++];
15     for(i=left;i<right;i++)
16     {
17         if(mid[i]==c)
18         break;
19     }
20     if(i>left&&i<right)
21     work(left,i);
22     if(i>=left&&i<right-1)
23     work(i+1,right);
24     printf("%c",c);
25 } 
26 
27 int main()
28 {
29     while(scanf("%s %s",pre,mid)==2)
30     {
31         //printf("%s %s\n",pre,mid);
32         counter = 0;
33         cnt = 0;
34         n=strlen(pre);
35 
36         work(0,n);
37         printf("\n");
38     }
39     return 0;
40 }

 

posted @ 2019-03-22 15:00  付玬熙  阅读(126)  评论(0编辑  收藏  举报