Often have the interview question is to know a tree's pre-sequence traversal and the middle sequence traversal lets you write the post-order traversal, this slowly painting is can draw out, but must be quick to get out or to understand the principle.
First of all, say three kinds of traversal: the so-called pre-order and the middle sequence are the sequence of traversing the root node. Sub-tree words according to the order from left to right, such as the former preface is: "Left-" right, the middle sequence is: Left-"in-" right.
Now the pre-order is: ABDGCEFH
The middle order is: DGBAECHF
If you want to ask for the post-ordered tree to be rebuilt, we have a rationale.
1. By the nature of the pre-order traversal can be known that a must be the root node of the tree
2. The middle sequence traversal in a before a is definitely the left subtree of a, after a is a right sub-tree.
OK, we can now divide the middle order into: DGB | A | Echf
The same Saozi right subtree is also contiguous in the preamble, so we can divide it into A | BDG | Cefh
You must have thought of recursion, yes, if only to look at the left sub-tree and as a new tree, the title becomes known pre-order: BDG, the middle order: DGB, the original tree. The right subtree is the same.
On the code, I wrote the Blind .... Forgive me.
#include <iostream>#include<string>using namespacestd;structnode{CharVal; Node*RC, *LC;} ; Node* Rebuild (stringPrestringmid) { intI, Len; Node*head =NewNode (); Head->val = pre[0] ; //cout << pre<< "" << mid << Endl;Len =mid.length (); for(i=0; i<len;i++) { if(pre[0]==Mid[i]) { if(i!=0) {Head->LC = Rebuild (Pre.substr (1, i), Mid.substr (0, i));//left dial hand tree } Else{Head->LC =NULL; } if(i!=len-1) {Head->RC = Rebuild (Pre.substr (i+1, len-1-i), Mid.substr (i+1, len-1-i));//Right sub-tree } Else{Head->RC =NULL; } } } returnhead;}voidAfter (Node *head) { if(head==NULL) { return ; } Else{ if(head->lc!=NULL) after (head-LC); if(head->rc!=NULL) after (head-RC); cout<< Head->val <<Endl; }}intMain () {stringPre, Mid; Node*head =NULL; while(cin>>pre>>mid) {Node*Head; Head=rebuild (Pre,mid); After (head); } return 0;}
Note that the substr parameter of this function means substr (start,length), when recursive Zuozi, the Shoko string pre-order and the length of the middle order are equal to I, not to the end of I that position.
C + + tree, knowing pre-order and sequence traversal