I have written the following code for constructing a tree from its inorder and preorder traversals. It looks correct to me but the final tree it results in does not have the same inorder output as the one it was built from. Can anyone help me find the flaw in this function?
public btree makeTree(int[] preorder, int[] inorder, int left,int right)
{
if(left > right)
return null;
if(preIndex >= preorder.length)
return null;
btree tree = new btree(preorder[preIndex]);
preIndex++;
int i=0;
for(i=left; i<= right;i++)
{
if(inorder[i]==tree.value)
break;
}
tree.left = makeTree(preorder, inorder,left, i-1);
tree.right = makeTree(preorder, inorder,i+1, right );
return tree;
}
Note: preIndex is a static declared outside the function.