首页 > 代码库 > UVa536 - Tree Recovery

UVa536 - Tree Recovery

题意

由前序遍历和中序遍历输出后序遍历

思路

前序遍历的第一个字母为根节点,从中序遍历中找到根节点的位置,其左边为左子树,右边为右子树,递归。

总结

从网上找了由前序遍历和中序遍历输出后序遍历 和 由中序遍历和后序遍历输出前序遍历 的代码,po在下面

不能由前序遍历和后序遍历得到中序遍历

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 typedef long long LL;
 7 const int maxn = 30;
 8 char pre[maxn], in[maxn];
 9 void Build_PostTree(char *in, char *pre, int len)
10 {
11     if(!len) return;
12     int i = 0;
13     for( ; i < len; i++)
14         if(in[i] == *pre) break;
15     Build_PostTree(in, pre+1, i); //Left
16     Build_PostTree(in + i + 1, pre + i + 1, len - i - 1); // Right
17     cout << *pre;
18     return;
19 }
20 int main()
21 {
22     //freopen("in.txt","r",stdin);
23     while(scanf("%s %s", pre, in) != EOF){
24         int len = strlen(pre);
25         Build_PostTree(in, pre, len);
26         cout << endl;
27     }
28     return 0;
29 }

 

由中序遍历和后序遍历输出前序遍历:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 typedef long long LL;
 7 const int maxn = 30;
 8 char in[maxn], post[maxn];
 9 void Build_PostTree(char *in, char *post, int len)
10 {
11     if(len == 0) return;
12     cout << *(post + len - 1);
13     int i = 0;
14     for( ; i < len; i++)
15         if(in[i] == *(post + len - 1)) break;
16     Build_PostTree(in, post, i); //Left
17     Build_PostTree(in + i + 1, post + i, len - i - 1); // Right
18     return ;
19 }
20 int main()
21 {
22    // freopen("in.txt","r",stdin);
23     while(scanf("%s %s", in, post) != EOF){
24         int len = strlen(post);
25         Build_PostTree(in, post, len);
26         cout << endl;
27     }
28     return 0;
29 }

 

UVa536 - Tree Recovery