Now that we have found the sequence of the left and right subtrees and the sequence traversal sequences, we can use the same method to construct the left and the sub-tree respectively. So, the next thing can be done in a recursive way.
The recursive code is as follows:
binarytreenode* Construct (int* preorder, int *inorder, int length)
{
if (preorder = = NULL | | inorder = = NULL | | length <= 0)
return NULL;
Return Constructcore (preorder,preorder+length-1,inorder,inorder+length-1);
}
binarytreenode* Constructcore (int* Startpreorder,int* Endpreorder,int* Startinorder,int* Endinorder)
The first number of a sequence traversal series is the value of the root node
int rootvalue = startpreorder[0];
binarytreenode* root = new Binarytreenode ();
Root->m_nvalue = Rootvalue;
Root->m_pleft = Root->m_pright = NULL;
if (Startpreorder = = Endpreorder)
{
if (Startinorder = = endinorder&& *startpreorder = = *startinorder)
return root;
Else
Throw std::exception ("Invalid input.");
}
Find the value of the root node in the middle sequence traversal
int* rootinorder = Startinorder;
while (Rootinorder <= endinorder&&*rootinorder! = rootvalue)
++rootinorder;
if (Rootinorder = = endinorder&&*rootinorder! = rootvalue)
Throw std::exception ("Invalid input.");
int leftlength = Rootinorder-startinorder;
int* leftpreorderend = Startpreorder + leftlength;
if (Leftlength > 0)
{
Build Zuozi
Root->m_pleft = Constructcore (Startpreorder + 1, leftpreorderend, Startinorder, rootInorder-1);
}
if (Leftlength < Endpreorder-startpreorder)
{
Building the right sub-tree
Root->m_pright = Constructcore (leftpreorderend + 1, endpreorder, Rootinorder + 1, endinorder);
}
return root;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Rebuilding a binary tree