Construct Special Binary Tree from given Inorder traversal

PROBLEM :

Given Inorder Traversal of a Special Binary Tree in which key of every node is greater than keys in left and right children, construct the Binary Tree and return root.

Examples:

Input: inorder[] = {5, 10, 40, 30, 28}
Output: root of following tree
         40
       /   \
      10     30
     /         \
    5          28

Input: inorder[] = {1, 5, 10, 40, 30,
                    15, 28, 20}
Output: root of following tree
          40
        /   \
       10     30
      /         \
     5          28
    /          /  \
   1         15    20

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;------------------------------------*/

tree * construct_special_tree(int [],int ,int) ;
int find_max_arrayPos(int [],int ,int ) ;

tree * special_Btree()
{
int no ;
cout<<"\n enter the number of element in the inorder array" ;
cin>>no ;

int a[no],i ;
for(i=0;i<no;i++)
cin>>a[i] ;

tree *root ;
root=construct_special_tree(a,0,no-1) ;
return root  ;
}

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

tree *temp=(tree*)malloc(sizeof(tree)) ;
temp->left=NULL ;
temp->right=NULL ;

if(start==end)
{
temp->info=a[start] ;
return temp ;
}

int p ;
p=find_max_arrayPos(a,start,end) ;

temp->info=a[p] ;
temp->left=construct_special_tree(a,start,p-1) ;
temp->right=construct_special_tree(a,p+1,end) ;

return temp ;
}

int find_max_arrayPos(int a[],int start,int end)
{
int i ,maxi;
maxi=start ;
for(i=start;i<=end;i++)
{
if(a[i]>a[maxi])
maxi=i ;
}
return maxi ;
}

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

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 )