UVa Two tree Reconstruction (first Order + middle order)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.