Currently I have the following algorithm which tries to create a tree from given inorder and preorder traversal and checks the postorder travesal of the tree so build with the given postorder?
But code seems to give runtime error! I am checking if a tree can even be made given the inorder and preorder traversal through a boolean possible.
My code to build tree is as below
static TreeNode buildTree(int start,int end,int root_pos)
{
if(start>end)
return null;
int key=preorder.get(root_pos);
TreeNode root=new TreeNode(key);
int i=start;
for(;i<=end;i++)
{
if(inorder.get(i)==key)
break;
}
if(i>end) //Case when we couldn't find root in given inorder
{
possible=false; //this tree cannot be made from given inorder and preorder traversals
return null;
}
else
{
root.left=buildTree(start, i-1, root_pos+1);
root.right=buildTree(i+1, end, root_pos+i-start+1);
return root;
}
}
What are the cases I am missing ?How can this be done?
I know how to construct tree from valid traversals,I want to know if the given traversals(which maybe invalid) are of the same tree?
The full problem statement is given here.