First, we look at the characteristics of the pre-order, the middle order, and the sequential traversal:
Pre-order Traversal:
1. Access the root node
2. Pre-sequence traversal Zuozi
3. Pre-sequence traversal right subtree
Middle Sequence Traversal:
1. Middle Sequence Traversal Zuozi
2. Access the root node
3. The middle sequence traverses the right sub-tree
Post-post traversal:
1. Post-Zuozi traversal
2. Post-the-loop traversal of right sub-tree
3. Access the root node
First, known pre-order, middle sequence traversal
Pre-sequence traversal: Gdafemhz
Middle Sequence Traversal: ADEFGHMZ
Algorithm Flow:
1 Determine the root, determine the left subtree, and determine the right subtree.
2 recursion in record.
3 recursively in the right subtree.
4 Prints the current root.
The order of sequential traversal is: AEFDHZMG
Programming Implementation:
#include <iostream>#include<fstream>#include<string>struct treenode{struct TreeNode*Left ; struct TreeNode*Right ; CharElem;};voidBinarytreefromorderings (Char* Inorder,Char* Preorder,intlength) { if(length = = 0) { //cout<< "Invalid length"; return; } TreeNode* node =NewTreeNode;//noice that [new] should is written out.Node->elem = *preorder; intRootindex = 0; for(; rootindex < length; rootindex++) { if(Inorder[rootindex] = = *preorder) Break; } // LeftBinarytreefromorderings (inorder, preorder +1, Rootindex); // RightBinarytreefromorderings (inorder + rootindex + 1, preorder + rootindex + 1, Length-(Rootindex + 1)); cout<<node->elem<<Endl; return;}intMainintargcChar*argv[]) {printf ("Hello world!\n"); Char* pr= "Gdafemhz"; Char* in= "ADEFGHMZ"; Binarytreefromorderings (in, PR,8); printf ("\ n"); return0;}
Second, the known order, the middle sequence traversal, to seek the pre-sequence traversal
Middle Sequence Traversal: ADEFGHMZ
Post-post traversal: AEFDHZMG
Algorithm Flow:
1 Determine the root, determine the left subtree, and determine the right subtree.
2 recursion in record.
3 recursively in the right subtree.
4 Prints the current root.
So, the pre-sequence traversal: Gdafemhz
Programming Implementation:
#include <iostream>#include<fstream>#include<string>struct treenode{struct TreeNode*Left ; struct TreeNode*Right ; CharElem;}; TreeNode* Binarytreefromorderings (Char* Inorder,Char* Aftorder,intlength) { if(length = = 0) { returnNULL; } TreeNode* node =NewTreeNode;//noice that [new] should is written out.Node->elem = * (aftorder+length-1); Std::cout<<node->elem<<Std::endl; intRootindex = 0; for(; rootindex < length; rootindex++)//a variation of the loop { if(Inorder[rootindex] = = * (aftorder+length-1)) Break; } node->left =binarytreefromorderings (inorder, Aftorder, Rootindex); Node->right = binarytreefromorderings (inorder + rootindex + 1, Aftorder + rootindex, Length-(Rootindex + 1)); returnnode;}intMainintargcChar**argv) { Char* af= "AEFDHZMG"; Char* in= "ADEFGHMZ"; Binarytreefromorderings (In, AF,8); printf ("\ n"); return0;}
Data structures and algorithms (6) Binary tree traversal