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.
I've some difficulties constructing the tree 'by hand'.
pre
shows that2
must be the root,in
shows that {1,3} are nodes of the left subtree,{5}
is the right subtree:But knowing this,
3
can't be the last element inpre
because it is clearly an element of the left subtree and we have a right subtree. Valid preorder traversals for these trees are{2,1,3,5}
or{2,3,1,5}
. But{2,1,5,3}
is impossible.Maybe the bug is not in this method but in your algorithm to create inorder and preorder traversals. Or, could it be, that you chose the values for
in[]
andpre[]
randomly?