Rebuilding a binary tree

Source: Internet
Author: User



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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.