Construct BST from given preorder traversal

PROBLEM :

Given preorder traversal of a binary search tree, construct the BST.

For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree.

     10
   /   \
  5     40
 /  \      \
1    7      50


--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;                       */

tree *construct_preorder_BST(int [],int ,int ) ;

tree *BSTree_preorder(tree *root)
{
int a[100],i,no ;

cout<<"\n enter the size of the array" ;
cin>>no ;
cout<<"\n enter elemets " ;
for(i=0;i<no;i++)
cin>>a[i] ;

root=construct_preorder_BST(a,0,no-1) ;
return root ;
}

tree *construct_preorder_BST(int a[],int start,int end)
{
if(start>end)
return NULL ;
tree *temp ;
temp=(tree*)malloc(sizeof(tree)) ;
temp->info=a[start] ;

int i ;
for(i=start+1;i<=end;i++)
{
if(a[i]>a[start])
break ;
}
temp->left=construct_preorder_BST(a,start+1,i-1) ;
temp->right=construct_preorder_BST(a,i,end) ;

return temp ;
}


---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )