Test instructions: Provides a pre-order traversal result, and a middle- order traversal result. Output sequential traversal results. Up to 26 nodes, i.e. from ' A ' ~ ' Z '.
Idea: Recursively set up a tree, and then recursively follow through. The result of a pre-order traversal is to do a DFS result, so you can traverse the sequence from left to right, and each encounter 1 letters as a node, establish a subtree with it as the root, until the subtree is established. How do you judge that the node that was created is the leaf node to conclude? This depends on the sequence of sequences, the middle sequence of each letter can be a sub-sequence of two halves, left is the left subtree, the right is a right sub-tree. Then the operation is in the sequence of the middle sequence, then the previous sequence as the auxiliary.
Note: At the beginning of the first order from the name of Prev, the result of the compilation error, changed to pre.
1#include <iostream>2#include <string>3#include <cstdio>4 using namespacestd;5 stringPre, Medi;6 intPoint ;7 structnode8 {9 CharC;TenNode *Left ; OneNode *Right ; A }; - -Node *createnode (Charc) the { -Node *p= (node*)New(node); -p->left=0; -p->right=0; +P->c=C; - returnp; + } Anode* DFS (intAintCurintb//cur is the root. In the interval [a, b], cur divides it into two subtrees trees for recursion. at { - if(a==b) - returnCreateNode (Medi[cur]); -Node *p=createnode (Medi[cur]);//Create the current node first - if(cur-a!=0)//find the left child . - { inpoint++; -P->left = DFS (A, Medi.find (Pre[point]), cur-1); to } + if(b-cur!=0)//find the right child - { thepoint++; *P->right = DFS (cur+1, Medi.find (Pre[point]), b); $ }Panax Notoginseng returnP//returns the entire subtree - } the voidSAO (node *p)//subsequent traversal tree + { A if(p->Left ) theSAO (p->Left ); + if(p->Right ) -SAO (p->Right ); $cout<< p->C; $ } - intMain () - { the //freopen ("Input.txt", "R", stdin); -Cin>> pre>>Medi;WuyiSao (DFS (0, Medi.find (pre[0]), pre.size ()-1) ); thecout<<Endl; - return 0; Wu}
AC Code
Hihocoder #1049: Post-post traversal