这类型的题(给中序和前后任一个,让求另外一个的)已经做了不下3、4遍了。。
再贴出来,代码风格可能会不大一样。。。应该是相比之前的有很多改进的。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include<iostream> #include<algorithm> #include<cstdio> #include<string> #include<deque> #include<map> #include<cstring> using namespace std; struct node { char l, r; node() { l = r = '*'; } node(char l1, char r1) { l = l1; r = r1; } }; map<char, node> dic; string in, post; inline int searchInTraversal(char v, int s, int e) { for (int i = s; i <= e; i++)if (in[i] == v)return i; return -1; } char buildTree(int is, int ie,int ps,int pe) { char father = post[pe]; if (is == ie && ps == pe) { dic[father] = node(); return father; } if (is > ie || ps > pe) { return '*'; } int posOfF = searchInTraversal(father, is, ie); int lTreeLen = posOfF - is; char l = buildTree(is, posOfF - 1, ps, ps + lTreeLen - 1); char r = buildTree(posOfF + 1, ie, ps + lTreeLen, pe - 1); dic[father] = node(l, r); return father; } void preTraversal(char node) { if (node == '*')return; cout << node; preTraversal(dic[node].l); preTraversal(dic[node].r); } int main() { cin >> in >> post; char f=buildTree(0, in.length() - 1, 0, post.length() - 1); preTraversal(f); } |