Rebuilding a binary tree and rebuilding a binary tree java

Source: Internet
Author: User

Rebuilding a binary tree and rebuilding a binary tree java



Now that we have found the pre-order traversal sequence and the middle-order traversal sequence of the left and right subtree respectively, we can use the same method to construct the left and right subtree respectively. Therefore, the next thing can be done using recursive methods.

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 the pre-order traversal sequence 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-order 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)
{
// Construct the left subtree
Root-> m_pLeft = ConstructCore (startPreorder + 1, leftPreorderEnd, startInorder, rootInorder-1 );
}
If (leftLength <endPreorder-startPreorder)
{
// Construct the right subtree
Root-> m_pRight = ConstructCore (leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder );
}
Return root;
}


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.