Here is a mathematical approach to achieving things in a very simplified way:
Used language: Java
`
/ * Algorithm for building a binary tree from specified Inorder and Preorder traversals. The following is the terminology:
i: represents the inorder array supplied
p: represents the presented array of pre-orders
beg1: starting index of the inorder array
beg2: starting index of the preorder array
end1: end index of inorder array
end2: end index of the preorder array
* /
public static void constructTree (Node root, int [] i, int [] p, int beg1, int end1, int beg2, int end2)
{
if(beg1==end1 && beg2 == end2) { root.data = i[beg1]; } else if(beg1<=end1 && beg2<=end2) { root.data = p[beg2]; int mid = search(i, (int) root.data); root.left=new Node(); root.right=new Node(); constructTree(root.left, i, p, beg1, mid-1, beg2+1, beg2+mid-beg1); System.out.println("Printing root left : " + root.left.data); constructTree(root.right, i, p, mid+1, end1, beg2+1+mid-beg1, end2); System.out.println("Printing root left : " + root.right.data); }
}
`
You need to call the function by executing the following code:
int[] i ={4,8,7,9,2,5,1,6,19,3,18,10};
If you need a more detailed explanation of the code, please indicate it in the comments. I would be happy to help :).