Construct Binary Tree from given Parent Array representation

PROBLEM :

Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation.

Input: parent[] = {1, 5, 5, 2, 2, -1, 3}
Output: root of below tree
          5
        /  \
       1    2
      /    / \
     0    3   4
         /
        6
Explanation:
Index of -1 is 5.  So 5 is root.
5 is present at indexes 1 and 2.  So 1 and 2 are
children of 5.
1 is present at index 0, so 0 is child of 1.
2 is present at indexes 3 and 4.  So 3 and 4 are
children of 2.
3 is present at index 6, so 6 is child of 3.


Input: parent[] = {-1, 0, 0, 1, 1, 3, 5};
Output: root of below tree
         0
       /   \
      1     2
     / \
    3   4
   /
  5
 /
6
     
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

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

tree* construct_Btree(int [],int,int ,int ) ;
int search_Index(int [],int ,int ,int ) ;

tree * Parent_array_BT()
{
int no,i ;
cout<<"\n enter the size of array" ;
cin>>no ;

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

tree *temp=construct_Btree(a,-1,0,no-1) ;
return temp ;
}

tree* construct_Btree(int a[],int ele,int start,int end)
{
int index,ind ;

ind=search_Index(a,start,end,ele) ;
if(ind==-1)
return NULL ;

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

index=search_Index(a,start,end,ind) ;

temp->left=construct_Btree(a,ind,start,end) ;

temp->right=construct_Btree(a,ind,index+1,end) ;

return temp ;
}

int search_Index(int a[],int start,int end,int ele)
{
int i ;
for(i=start;i<=end;i++)
{
if(a[i]==ele)
return i ;
}
return -1 ;
}

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

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 )