# Reconstruction of binary tree by combination of middle order traversal and first order traversal

Problem Description:

Enter the result of preorder traversal and inorder traversal of a binary tree. Please rebuild the binary tree. It is assumed that the results of the input preorder traversal and preorder traversal do not contain duplicate numbers. For example, if the sequence {1,2,4,7,3,5,6,8} and the sequence {4,7,2,1,5,3,8,6} are input, the binary tree will be reconstructed and returned.

Analysis:

Use recursion to implement this problem

Code implementation:

```typedef struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
}TreeNode;

TreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder,int* endInorder)
{
//The first node traversed in sequence is the root node
int rootVal = startPreorder[0];
TreeNode* root = new TreeNode();
root->val = rootVal;
root->left = root->right = NULL;

if (startPreorder == endPreorder) //First order traversal has only one node, the exit of recursion
{
if (startInorder == endInorder  &&  *startPreorder == *startInorder) //There is only one node in the middle order traversal, and the first order and the middle order are equal
return root;
else
throw std::exception("Invalid input.");
}

//Find the root node in the middle order sequence
int* rootInorder = startInorder;
while (rootInorder <= endInorder && *rootInorder != rootVal)
++rootInorder;

if (rootInorder == endInorder && *rootInorder != rootVal) //If the root node cannot be found in the middle order, the input data is wrong
throw std::exception("Invalid input.");

//Determining the intervals of left and right trees in the first and middle order
int leftLength = rootInorder - startInorder; //Length of left subtree in middle order
int *leftPreorderEnd = startPreorder + leftLength; //In the first order, the left subtree ends

if (leftLength > 0) //Build left subtree (left subtree with nodes)
root->left = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1);
if (leftLength < endPreorder - startPreorder) //Build right subtree (right subtree with nodes)
{
root->right = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder);
}

return root;
}

TreeNode* Construct(int* preOrder, int* inOrder, int length)//structure
{
if (preOrder == NULL || inOrder == NULL || length <= 0)
return NULL;

return ConstructCore(preOrder, preOrder + length - 1, inOrder, inOrder + length - 1);
}

int main()
{
int preOrder[] = { 1, 2, 4, 7, 3, 5, 6, 8 };
int inOrder[] = { 4, 7, 2, 1, 5, 3, 8, 6 };
int len = sizeof(preOrder) / sizeof(preOrder[0]);
TreeNode* root = Construct(preOrder, inOrder, len);
return 0;
}```

Reflection:

1. Medium sequence and subsequent reconstruction?

2. Reconstruction of middle order and subsequent combination of string representation

3. Reconstruction by array with 2i+1 / 2i+2 Relationship

4. Create when entering

Posted by darkknightgaury on Thu, 07 Nov 2019 13:50:36 -0800