Given a preorder traversal of a BST.I have to construct the BST. Can I construct the BST from the preorder traversal simply by creating a empty BST and then inserting the elements in preorder traversal one by one starting from the first element and ending at the last element into the empty BST?
For example,consider the following BST:-
10
/ \
5 40
/ \ \
1 7 50
Its preorder traversal is :
10 5 1 7 40 50
By creating a empty BST and then inserting elements in preorder traversal one by one starting from the first element gives me the exact BST explained as follows:
(empty tree)
insert first element of preorder traversal: 10
10
insert second element of preorder traversal: 5
10
/
5
similarly,
10
/
5
/
1
10
/
5
/ \
1 7
10
/ \
5 40
/ \
1 7
10
/ \
5 40
/ \ \
1 7 50
Here I have constructed the exact BST just by inserting the elements in preorder traversal one by one into an empty tree. Will this algorithm work at all cases?Is there any case where this algorithm wont work?
void insertIntoTree(struct* Node,int val)
{
if(Node == NULL)
{
Node = createNewNode(val);
return;
}
if(val < Node->val)
insertIntoTree(Node->left,val);
else
insertIntoTree(Node->right,val);
}
int main()
{
int preorderlist[] = { 10,5,1,7,40,50};
for(int i=0;i <= preorderlist.size();i++)
{
insertIntoTree(TreeRoot,preorderlist[i]);
}
}