Construct a special tree from given preorder traversal

PROBLEM :

Given an array ‘pre[]’ that represents Preorder traversal of a spacial binary tree where every node has either 0 or 2 children. One more array ‘preLN[]’ is given which has only two possible values ‘L’ and ‘N’. The value ‘L’ in ‘preLN[]’ indicates that the corresponding node in Binary Tree is a leaf node and value ‘N’ indicates that the corresponding node is non-leaf node. Write a function to construct the tree from the given two arrays.


Example:

Input:  pre[] = {10, 30, 20, 5, 15},  preLN[] = {'N', 'N', 'L', 'L', 'L'}
Output: Root of following tree
          10
         /  \
        30   15
       /  \
      20   5

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

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

tree * create_special_btree(int a[],char b[],int *start,int end)


tree * Special_Btree()
{
int no ;
cout<<"\n how many elements to be entred in the array " ;
cin>>no ;

int i,a[no] ;
char s[no] ;

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

cout<<"\n enter the status node array " ;
for(i=0;i<no;i++)
cin>>s[i] ;

int start=0 ;

return create_special_btree(a,s,&start,no-1) ;

}

tree * create_special_btree(int a[],char b[],int *start,int end)
{
if((*start)>end)
return NULL ;

tree *temp ;
temp=(tree*)malloc(sizeof(tree)) ;

if((b[(*start)]=='L')||(b[(*start)]=='l'))
{
temp->info=a[(*start)] ;
temp->left=NULL ;
temp->right=NULL ;
(*start)++ ;
}
else
{
temp->info=a[(*start)] ;
(*start)++ ;
temp->left=create_special_btree(a,b,&(*start),end) ;
temp->right=create_special_btree(a,b,&(*start),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 )