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.