Find a pair with given target in BST

PROBLEM :

Given a 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.

Input:
First line consists of T test cases. First line of every test case consists of N and target, denoting the number of elements in bst and target sum. Second line consists of elements of BST.

Output:
Return True if target sum pair is found else False.

Constraints:
1<=T<=100
1<=N<=100

Example:
Input:
2
7 10
1 2 3 4 5 6 7
7 33
15 10 20 8 12 16 25

Output:
1
1

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

/*Complete the function below
Node is as follows
struct node
{
    int val;
    struct node *left, *right;
};
*/

bool isPairPresent(struct node *root, int target)
{
    if(!root)
        return false ;
   
    stack<struct node*> sta1 ;
    stack<struct node*> sta2 ;
   
    bool done1,done2 ;
    done1=false ;
    done2=false ;
   
    int val1,val2 ;
    struct node *curr1, *curr2 ;
    curr1=root ;
    curr2=root ;
   
    while(true)
    {
        while(!done1)
        {
            if(curr1)
            {
                sta1.push(curr1) ;
                curr1=curr1->left ;
            }
            else
            {
                if(sta1.empty())
                    done1=true ;
                else
                {
                    curr1=sta1.top() ;
                    sta1.pop() ;
                    val1=curr1->val ;
                    curr1=curr1->right ;
                    done1=true ;
                }
            }
        }
       
        while(!done2)
        {
            if(curr2)
            {
                sta2.push(curr2) ;
                curr2=curr2->right ;
            }
            else
            {
                if(sta2.empty())
                    done2=true ;
                else
                {
                    curr2=sta2.top() ;
                    sta2.pop() ;
                    val2=curr2->val ;
                    curr2=curr2->left ;
                    done2=true ;
                }
            }
        }
     
        if((val1!=val2)&&((val1+val2)==target))
            return true ;
           
        else if((val1+val2)<target)
            done1=false ;
           
        else if((val1+val2)>target)
            done2=false ;
           
        if(val1>=val2)
            return false ;
    }
}

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

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 )