This blog continues to organize the topic tree based on some OJ questions. Will be updated one after another...
1. tree traversal
Tree definition: connected undirected graph without loops.
Example
1. Restoration of the POJ 2255 Tree Recovery Tree
Question Analysis:
This question is abstracted as follows: "The descending traversal order is determined by the pre-order traversal of the tree and the middle-order traversal order ". In fact, we have seen the following sentence on various materials a long time ago, we can uniquely identify a binary tree ".. But what is the idea of the algorithm and how it is implemented? I think many people will not explore it very much, that is, simply remember this sentence, remember as a theorem...
The following is an algorithm for obtaining the post-order traversal sequence from the pre-order traversal sequence and the middle-order traversal sequence.
Description: first, the root node is determined by the first node in the preorder traversal sequence. Then find the node in the ordinal traversal sequence. Then, output the number of elements before the node, and traverse the elements with the same number in the sequence in the forward Order (except for the first root node )... At this time, we can get the pre-order traversal sequence of the root node, the left subtree, and the middle-order traversal virtual column, the right subtree's pre-order traversal sequence, and the middle-order traversal sequence. .. The next task is continuous recursion .....
The implementation is as follows:
/*** Obtain the post-order sequence from the pre-order sequence and the middle-order sequence */string solve (string pre, string in) {if (in. length () = 1) {// return in;} else if (in. length () = 0) {return "";} int m = in. find (pre [0]); // locate the root node position in the middle sequence // The traversal order of the Post-order traversal is: returns solve (pre. substr (1, m), in. substr (0, m) + solve (pre. substr (m + 1), in. substr (m + 1) + pre [0];}
The solution to this question is as follows:
/** POJ_2255_1.cpp ** Created on: July 15, June 8, 2014 * Author: Administrator */# include
# Include
# Include
Using namespace std;/*** obtain the post-order sequence from the pre-order sequence and the middle-order sequence */string solve (string pre, string in) {if (in. length () = 1) {// return in;} else if (in. length () = 0) {return "";} int m = in. find (pre [0]); // locate the root node position in the middle sequence // The traversal order of the Post-order traversal is: returns solve (pre. substr (1, m), in. substr (0, m) + solve (pre. substr (m + 1), in. substr (m + 1) + pre [0];} int main () {string back; string pre; string in; while (cin> pre> in) {back = solve (pre, in); cout <back <