首页 > 代码库 > 由中序遍历和后序遍历求前序遍历

由中序遍历和后序遍历求前序遍历

 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 }

 

由中序遍历和后序遍历求前序遍历