For example, if the first sequence string is dbacgf, the first node in the first sequence must be the root node, so that we know that the root node is D.
Let's look at the central order. In the middle order string, all the nodes in the front of the root node are in the left subtree, abcdefg, so ABC in front of node D is the middle order string in the left subtree.
Let's look at the continuation string dbacepidermal N. Because the node on the left subtree is ABC, we can get the continuation string of the Left subtree: Bac. With the forward sequence string of the Left subtree, Bac,
We can recursively create the left subtree with the string ABC. You can also create a right subtree. The beauty of programming involves this algorithm.
// Date: 6/29
// Known pre-order and Middle-order re-build a binary tree
# Include <stdio. h>
# Define treelen 6
Typedef struct Node
{
Char value;
Node * pleft;
Node * pright;
} Node;
Void rebuild (char * ppreorder,
Char * pinorder,
Int treelen,
Node ** proot)
{
If (ppreorder = NULL | pinorder = NULL)
{
Return;
}
// Obtain the root node
Node * ptemp = new node;
Ptemp-> value = * ppreorder;
Ptemp-> pleft = NULL;
Ptemp-> pright = NULL;
// Save the output Root Node
If (* proot = NULL)
{
* Proot = ptemp;
}
If (treelen = 1)
{
Return;
}
// Find the intensity of the subtree and then Recursion
Char * porginorder = pinorder;
Char * pleftend = pinorder;
Int ntemplen = 0;
While (* ppreorder! = * Pleftend)
{
If (ppreorder = NULL | pleftend = NULL)
{
Return;
}
Ntemplen ++;
If (ntemplen> treelen)
{
Break;
}
Pleftend ++;
}
// Len of left child tree
Int nleftlen = 0;
Nleftlen = (INT) (pleftend-porginorder );
// Len of right child tree
Int nrightlen = 0;
Nrightlen = TreeLen-nLeftLen-1;
// Rebuild left Tree
If (nleftlen> 0)
{
Rebuild (ppreorder + 1, pinorder, nleftlen, & (* proot)-> pleft ));
}
If (nrightlen> 0)
{
Rebuild (ppreorder + nleftlen + 1, pinorder + nleftlen + 1, nrightlen, & (* proot)-> pright ));
}
}
Int main ()
{
Char szpreorder [treelen] = {'A', 'B', 'D', 'C', 'E', 'F '};
Char szinorder [treelen] = {'D', 'B', 'A', 'E', 'C', 'F '};
Node * proot = NULL;
Rebuild (szpreorder, szinorder, treelen, & proot );
}