Test instructions is to give first order and middle order, and to find out the sequence.
The first sequence traversal first accesses the root node, through the root node can divide the sequence into the left sub-tree part and the right subtree part, I built a stack, because the post-order traversal finally accesses the root node, so the root node of each access is put into the stack. Because the post-sequential traversal is first the left dial hand tree and then the right subtree, recursion is recursive to the right subtree, and then to the left subtree recursively.
After writing the program has a mistake, looked for a long time to find out, is that I originally in the calculation of the number of left subtree, is this calculation, Pre2=mid-pre, but when Pre>mid, it is wrong. The right way to calculate the left subtree should be the following.
1#include <iostream>2#include <cstring>3#include <stack>4 using namespacestd;5 6 Chart1[ -], t2[ -];7stack<Char>map;8 intlength;9 Ten voidSolveintPreintMidintlen) One { A Map.push (T1[pre]); - inti =mid; - while(T2[mid]! = T1[pre]) mid++;//finding the same node in the sequence of sequences as the preceding sequence the intPre2 = Mid-i;//Number of Zuozi - intMid2 = Len-1-Pre2;//Number of right sub-trees - if(Mid2 >=1) -Solve (pre + Pre2 +1, Mid +1, MID2); + if(Pre2 >=1) -Solve (pre +1, Mid-Pre2, pre2); + } A at - intMain () - { - while(Cin >> T1 >>T2) - { -Length =strlen (t1); inSolve0,0, length); - while(!map.empty ()) to { + Chars =map.top (); -cout <<s; the Map.pop (); * } $cout <<Endl;Panax Notoginseng } - return 0; the}
UVa Two tree Reconstruction (first Order + middle order)