Ideas:
The first node of the first order sequence is to construct the root node of the two-fork tree, and to find the root node of the binary tree in the sequence, then the middle sequence of the left subtree of the root node is the left of the root node, and the middle sequence of the right sub-tree of the root node is the right. The first sequence of the first sequence root node is the Saozi of its right subtree. With the position of the root node in the sequence, we know the position of the sequence of the Saozi right subtree. In this way, you know the sequence of two subtrees of the root node.
Then, after constructing the root node, it is possible to recursively invoke the function to collude with the Saozi right subtree of the root node.
The above is a two-fork tree recovery.
The sequential traversal of the binary tree is also recursive.
The code is as follows:
String.find () returns the index of the lookup element
String.substr (A, b) intercept the B element starting from the element a subscript
#include <iostream>
#include <cstdio>
#include <string>
using namespace Std;
struct Node
{
char data;
Node * LCHILD;
Node * RCHILD;
};
node* Creattree (string Pre, string in)
{
Node * root = NULL; The initialization of the tree
if (pre.length () > 0)
{
root = new Node; The memory required for the structure to be requested for the root node
Root->data = pre[0]; The first element of the first order sequence is the root node.
int index = In.find (root->data); Finding root node locations in sequence sequences
Root->lchild = Creattree (pre.substr (1, index), in.substr (0, index)); Recursive creation of Zuozi
Root->rchild = Creattree (pre.substr (index + 1), IN.SUBSTR (index + 1)); Recursive creation of right sub-tree
}
return root;
}
void Postorder (Node * root)//recursive post-post traversal
{
if (root = NULL)
{
Postorder (Root->lchild);
Postorder (Root->rchild);
cout<<root->data;
}
}
int main ()
{
String Pre_str, In_str;
Node *root;
while (CIN>>PRE_STR>>IN_STR)
{
Root = Creattree (Pre_str, IN_STR);
Postorder (root);
cout<<endl;
}
return 0;
}
The sequential traversal sequence and the middle sequence traversal sequence of the binary tree are known, and the sequential traversal sequence is obtained.