由中序遍历和前序遍历序列求树的后序
题目虽然简单但是确实比较经典, 所以还是记录一下吧
这次尝试一下用map容器存储树
这样既能表面上实现树的顺序存储, 又不会浪费太多空间 :)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <list>
#include <cassert>
#include <iomanip>
#pragma warning(disable:4996) //关掉4996警告
/*
Uva 536
*/
using namespace std;
map<int, char> Tree; // 尝试用map存储树
void Build(const char * pre, const char * inorder, int root, int N) {
if ( N == 0 ) return;
Tree[root] = *pre;
int tmp = 0;
while ( inorder[tmp] != Tree[root] ) tmp++;
Build(pre + 1, inorder, root * 2, tmp);
Build(pre + tmp + 1, inorder + tmp + 1, root * 2 + 1, N - tmp - 1);
}
void PostTrav(int node) {
if ( Tree[node * 2] ) PostTrav(node * 2);
if ( Tree[node * 2 + 1] ) PostTrav(node * 2 + 1);
cout << Tree[node];
}
int main( ) {
//freopen("input.txt", "r", stdin);
string pre, inorder;
while ( cin >> pre ) {
cin >> inorder;
Tree.clear( );
Build(pre.c_str(), inorder.c_str(), 1, pre.length());
PostTrav(1);
cout << endl;
}
//system("pause");
return 0;
}