Find a pair with given sum in a Balanced BST

PROBLEM :

Given a Balanced Binary Search Tree and a target sum, write a function that returns true if there is a pair with sum equals to target sum, otherwise return false. Expected time complexity is O(n)
Any modification to Binary Search Tree is not allowed. Note that height of a Balanced BST is always O(Logn).



Example :
 for the above tree if user inputed target sum as 35 the output will be sum of 10,25 and 15,20
 
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

The Brute Force Solution is to consider each pair in BST and check whether the sum equals to X. The time complexity of this solution will be O(n^2).

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 pair_sum_BST(tree *root,int ele)
{
int s,i ;
s=size_tree(root) ;
int array[s] ;
i=0 ;
inorder_array_fill(root,array,&i) ;

int a,b ;
a=0,b=s-1 ;
while(a<b)
{
if(array[a]+array[b]<ele)
a++ ;
else if(array[a]+array[b]>ele)
b-- ;
else
{
cout<<"\n sum pair found as "<<array[a]<<" and "<<array[b] ;
a++ ;
                        b-- ;
}
}
cout<<"\n No such sum pair found " ;
}

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 )