POJ 2255

题意:根据前序遍历和中序遍历,求后序遍历

 

统计:

200K, 16ms, 1Y, 35min

 

#include <iostream> #include <algorithm> #include <string> #define F(i,a,b) for (int i=a;i<=b;i++) using namespace std; char lc[27], rc[27]; char build_tree(string pre, string in) { char root=pre[0]; //cout << "pre: " << pre << " in: " << in << endl; if (pre.length()>1) { // cout << "pre: " << pre << " in: " << in << endl; int pos=in.find_first_of(root); //cout << pos << " " << in[pos] << endl; int lena=pos, lenb=pre.length()-pos-1; if (lena!=0) lc[ (int)(root-'A') ]=pre[1]; if (lenb!=0) rc[ (int)(root-'A') ]=pre[1+lena]; build_tree( pre.substr(1,lena), in.substr(0,lena) ); build_tree( pre.substr(pos+1, lenb), in.substr(lena+1, lenb) ); } return root; } void postorder(char id) { if (lc[ (int)(id-'A') ]!=id) postorder( lc[ (int)(id-'A') ] ); if (rc[ (int)(id-'A') ]!=id) postorder( rc[ (int)(id-'A') ] ); cout << id; } int main() { //freopen ("in.txt", "r", stdin); string str1, str2; while (cin >> str1 >> str2) { F(i,0,25) lc[i]=(char)(i+'A'), rc[i]=(char)(i+'A'); char root=build_tree(str1, str2); postorder(root); cout << endl; } return 0; }

你可能感兴趣的:(POJ 2255)