The nodes of a binary tree indicate:
struct NODE
{
node* Pleft;
node* Pright;
Char Chvalue;
};
Assuming that there is a pre-order and middle-order traversal result, you want to reconstruct the tree with an algorithm.
Analysis:
Rebuild.cpp: Based on pre-order and middle order results, the root node of the re-achievement
Defines the length of the tree, for the simple implementation of the subsequent calls, directly with the macro defines the total number of tree nodes
#define Treelen 6
Tree node
struct NODE
{
node* Pleft;
node* Pright;
Char chvalue;//node value
};
void ReBuild (char* ppreorder, char *pinorder, int ntreelen, node** proot)
{
Check boundary conditions
if (Ppreorder = = NULL | | pinorder = = NULL)
Return
Get the first node of a pre-order traversal
node* ptemp = new NODE;
Ptemp->chvalue = *ppreorder;
Ptemp->pleft = NULL;
Ptemp->pright = NULL;
If the node is empty, copy the current node to the root node
if (*proot = = NULL)
*proot = ptemp;
If the current tree has a length of 1, it is already the last node.
if (Ntreelen = = 1)
Return
Looking for subtree length
char* porginorder = Pinorder;
char* pleftend = Pinorder;
int ntemplen = 0;
Find the end of Zuozi
while (*ppreorder! = *pleftend)
{
if (Ppreorder = = NULL | | pleftend = = NULL)
Return
ntemplen++;
if (Ntemplen > Ntreelen)
Break
pleftend++;
}
Look for the length of the left sub-tree
int nleftlen = 0;
Nleftlen = (int) (pleftend-porginorder);
Looking for the right subtree length
int nrightlen = 0;
Nrightlen = ntreelen-nleftlen-1;
Rebuilding Zuozi
if (Nleftlen > 0)
ReBuild (Ppreorder + 1, Pinorder, Nleftlen, & ((*proot)->pleft));
Rebuilding the right sub-tree
if (Nrightlen > 0)
ReBuild (Ppreorder +nleftlen+1, pinorder+nleftlen+1, Nrightlen, & ((*proot)->pright));
}
Example Call code
int main (int argc, char* argv[])
{
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);
}
Rebuilding a binary tree