Find if there is a triplet in a Balanced BST that adds to zero

PROBLEM :

Given a Balanced Binary Search Tree (BST), write a function isTripletPresent() that returns true if there is a triplet in given BST with sum equals to 0, otherwise returns false. Expected time complexity is O(n^2) . You can modify given Binary Search Tree. Note that height of a Balanced BST is always O(Logn)

For example, isTripletPresent() should return true for following BST because there is a triplet with sum 0, the triplet is {-13, 6, 7}.



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

The Brute Force Solution is to consider each triplet in BST and check whether the sum adds upto zero. The time complexity of this solution will be O(n^3).

BETTER SOLUTION :

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

int size_tree(tree*) ;
void inorder_array_fill(tree* ,int [],int *) ;

void triplet_tree(tree *root)
{
int h,i ;
h=size_tree(root) ;
i=0 ;
int array[h] ;
inorder_array_fill(root,array,&i) ;

int a,b,c ;

for(i=0;i<h;i++)
{
a=array[i] ;
b=i+1 ;
c=h-1 ;
while(b<c)
{
if(a+array[b]+array[c]==0)
{
cout<<" Triplate found !!! elements are "<<a<<" "<<array[b]<<" "<<array[c] ;
break ;
}
else if(a+array[b]+array[c]<0)
b++ ;
else
c-- ;

}
}

cout<<" \n No Triplate preasent " ;
}


int size_tree(tree* root)
{
if(root==NULL)
return 0 ;

return ((size_tree(root->left))+(size_tree(root->right))+1) ;
}

void inorder_array_fill(tree* root,int a[],int *s)
{
    if(root==NULL)
        return  ;
     
    inorder_array_fill(root->left,a,&(*s)) ;
    a[(*s)++]=root->info ;
    inorder_array_fill(root->right,a,&(*s)) ;
 
}

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

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 )