The specific algorithm is to use the first letter of the preface (root node) to find the letter, the middle sequence is divided into 2 sections, the previous section is left subtree, length len_l, the following section is right subtree, length len_r. And the length of the pre-order string can be divided into such 2 sections according to the length len_l and len_r of the preceding sequence analysis. Then build it recursively.
Such as:
Pre-sequence "abdhlekcfg";
"HLDBEKAFCG" in the sequence of sequences;
1. Use a to sequence search, divide it into Hldbek and FCG, the length of Zuozi is 6, the right subtree is 3.
2. The pre-sequence sequence is divided into Bdhlek and cfg according to the length of the left and right sub-tree of the preceding sentence.
3. Recursive builds, R (Hldbek,bdhlek) and R (fcg,cfg).
#include <string> #include <iostream> #include <assert.h>using namespace std;struct node{char c; Node *lchild, *rchild;}; Class tree{private:string preorder, inorder; Node *root;public:tree () {root = NULL; cout<< "Input string:\n"; while (Cin>>preorder>>inorder)//abdhlekcfg HLDBEKAFCG {rebuildtree (preorder, inorder, Root) ; Postorder (root); cout<< "\ninput-string:\n"; }} ~tree () {} void Rebuildtree (String prestr, String instr, node* &ptemp)//pointer reference {ASSERT (Prestr.le Ngth () = = Instr.length ()); if (prestr.length () = = 0) {return; } ptemp = new node; char c; c = ptemp->c = Prestr[0]; Ptemp->lchild = NULL; Ptemp->rchild = NULL; int pos = Instr.find (c); int left = pos; int right = Instr.length ()-pos-1; if (Left > 0) { Rebuildtree (PRESTR.SUBSTR (1, left), Instr.substr (0, left), ptemp->lchild); } if (right > 0) {rebuildtree (Prestr.substr (left+1, right), Instr.substr (left+1, right), Ptem P->rchild); }} void Postorder (node *p) {if (P! = NULL) {postorder (p->lchild); Postorder (P->rchild); cout<<p->c; }}};void Main () {tree T; System ("Pause");}
Pre-order sequence, reconstruction of binary tree, output order