In the case of a binary tree, a binary tree can be determined by its pre-order and middle-order or sequence-and-order traversal sequences.
Then for the known pre-order and the sequence of sequences, the order sequence is to restore the binary tree first, and then after the sequential traversal can be.
The structure of the binary tree node is defined as follows:
struct treenode{ char value; *leftchild; *rightchild;};
The implementation code is as follows:
#include <stdio.h>#include<string.h>#include<stdlib.h>TreeNode*AllocateNode () {TreeNode* node = (treenode*)malloc(sizeof(TreeNode)); Node->leftchild =nullptr; Node->rightchild =nullptr; returnnode;}Charprestr[ -], instr[ -];voidPostorder (TreeNode *T) { if(T->leftchild! =nullptr) {Postorder (T-leftchild); } if(T->rightchild! =nullptr) {Postorder (T-rightchild); } printf ("%c", t->value);} TreeNode* Builttree (intStart1,intEnd1,intStart2,intEnd2) {TreeNode*node =AllocateNode (); Node->value =Prestr[start1]; intNodeindex; for(inti = Start2; I <= End2; ++i)if(Prestr[start1] = =Instr[i]) {Nodeindex=i; Break; } if(Nodeindex! =Start2) {Node->leftchild = Builttree (Start1 +1, Start1 + (NODEINDEX-START2), Start2, Nodeindex-1); } if(Nodeindex! =End2) {Node->rightchild = Builttree (Start1 + (NODEINDEX-START2) +1, End1, Nodeindex +1, End2); } returnnode;}voidMainvoid) {scanf ("%s", PRESTR); scanf ("%s", INSTR); intPrelen =strlen (PRESTR); intInlen =strlen (INSTR); TreeNode*root = Builttree (0, Prelen-1,0, Inlen-1); Postorder (root);}
On the problem of binary tree 1-known pre-order, middle order for sequential traversal