Find a pair with given target in BST | Practice | GeeksforGeeks

Given a Binary Search Tree and a target sum. Check whether there's a pair of Nodes in the BST with value summing up to the target sum. 
Example 1:
Input:
        2
      /   \
     1     3
sum = 5
Output: 1 
Explanation: 
Nodes with value 2 and 3 sum up to 5.

Example 2:
Input:
           6
          /    
         5     
        /
       3 
     /  \
    1    4
sum = 2
Output: 0 
Explanation: 
There's no pair that sums up to 2.

Your Task:
You don't need to read input or print anything. Your task is to complete the function isPairPresent() that takes a root node and a target value as a parameter and returns 1 if there's a pair of Nodes in the BST with values summing up to the target sum, else returns 0. 
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of Nodes ≤ 105
1 ≤ Sum ≤ 106
0
sagrikasoni2 days ago
class Solution
{
    // root : the root Node of the given BST
    // target : the target sum
    public ArrayList<Integer>inorder (Node root, ArrayList<Integer> a){
        if(root!=null){
        if (root.left!=null)
         inorder(root.left,a);
         a.add(root.data);
         if(root.right!=null)
         inorder(root.right,a);
        }
        return a;
    }
    public int isPairPresent(Node root, int target)
    {
        ArrayList<Integer> ar = new ArrayList<Integer>();
        inorder(root,ar);
        HashSet<Integer> hs = new HashSet<Integer>();
        for(int i =0;i<ar.size();i++){
            if(hs.contains(target-ar.get(i)))
              return 1;
             hs.add(ar.get(i));
        }
        
        return 0;
        
        
    }
}
0
adarshgupta4012 weeks ago
Easy JAva Code-
class Solution
{
    public int isPairPresent(Node root, int k)
    {
       ArrayList<Integer> list = new ArrayList<>();
        inorder(root, list);
        int i=0, j=list.size() -1;
        while(i< j){
            int sum = list.get(i) + list.get(j);
            if( sum == k ) return 1;
            else if(sum > k ) j--;
            else i++;
        }
        
        return 0;
    }
    public void inorder( Node root, ArrayList<Integer> list){ 
        if(root == null) return ;
        inorder(root.left, list);
        list.add( root.data);
        inorder(root.right, list);
    }
}
0
amishasahu3282 weeks ago
class BSTIterator
{
    stack<Node*> st;
    bool reverse = true;
    // reverse -> true [before]
    // reverse -> false [next]
    public:
    BSTIterator(Node *root, bool isReversed){
        reverse = isReversed;
        pushAll(root);
    }
    int next()
    {
        Node *root = st.top();
        st.pop();
        if(!reverse) pushAll(root->right);
        else pushAll(root->left);
        return root->data;
    }
    void pushAll(Node *root)
    {
        while(root)
        {
            st.push(root);
            if(!reverse) root = root->left;
            else root = root->right;
        }
    }
    
};
class Solution{
  public:
    // root : the root Node of the given BST
    // target : the target sum
    int isPairPresent(struct Node *root, int target)
    {
    //add code here.
        if(!root) return 0;
         BSTIterator left(root, false);
         BSTIterator right(root, true);
         
         int i = left.next();
         int j = right.next();
         while(i < j)
         {
             if(i + j == target) return 1;
             else if(i + j < target) i = left.next();
             else j = right.next();
         }
         return 0;
    }
};
0
dronzerdracel3 weeks ago
Inorder traversal|2 pointer
void solve(struct Node *root,vector<int>&v){
        if(!root)
         return;
        solve(root->left,v);
        v.push_back(root->data);
        solve(root->right,v);
    }
    int isPairPresent(struct Node *root, int target)
    {
    //add code here.
    vector<int>v;
    solve(root,v);
    int i=0,j=v.size()-1;
    while(i<j){
        int sum=v[i]+v[j];
        if(sum==target)
         return 1;
        else if(sum>target)
         j--;
        else
         i++;
    }
    return false;
    }
0
parthbabbar0012 months ago
class Solution{
  private:
  void inOrder(struct Node *root,vector<int>& ans){
      if(root==NULL){
          return ;
      }
      
      inOrder(root->left,ans);
      ans.push_back(root->data);
      inOrder(root->right,ans);
      
  }

  public:
    // root : the root Node of the given BST
    // target : the target sum
    int isPairPresent(struct Node *root, int target)
    {
        vector<int> ans;
        inOrder(root,ans);
        int i=0;
        int j=ans.size()-1;
        while(i<j){
            int sum = ans[i] + ans[j];
            if(sum==target){
                return 1;
            }
            else if(sum>target){
                j--;
            }else{
                i++;
            }
        }
        
        return 0;
    }
0
lindan1232 months ago
 unordered_map<int,int> m;
    vector<int> vec;
    void traversel(struct Node* root)
    {
        if(!root)return ;
        
        traversel(root->left);
        m[root->data]++;
        vec.push_back(root->data);
        traversel(root->right);
    }
    int isPairPresent(struct Node *root, int tar)
    {
        traversel(root);
        
        for(int i=0;i<vec.size();i++)
        {
            if(vec[i]<tar)
            {
                int num = tar - vec[i];
                if(m.find(num)!=m.end())
                {
                    return 1;
                }
            }
            else
            {
                return 0;
            }
        }
        return 0;
    }
Time Taken : 1.5sec
Cpp
+1
charigardash2 months ago
class Solution
{
    // root : the root Node of the given BST
    // target : the target sum
    Stack<Node> s1,s2;
    void find1(Node a){
        while(a!=null){
            s1.push(a);
            a=a.left;
        }
    }void find2(Node a){
        while(a!=null){
            s2.push(a);
            a=a.right;
        }
    }
    public int isPairPresent(Node root, int target)
    {
        // Write your code here
        s1=new Stack<>();
        s2=new Stack<>();
        find1(root);
        find2(root);
        while(s1.size()>0&&s2.size()>0){
            if(s1.peek().data+s2.peek().data==target)return 1;
            else if(s1.peek().data+s2.peek().data>target){
                Node n=s2.peek();
                s2.pop();
                find2(n.left);
            }else{
                Node n=s1.peek();
                s1.pop();
                find1(n.right);
            }
        }return 0;
    }
}
0
pratyushpandey7302 months ago
class Solution{
  public:
    // root : the root Node of the given BST
    // target : the target sum
    
    void helper(struct Node *root, vector<int> &v){
        
        if(root==NULL) return;
        
        v.push_back(root->data);
        helper(root->left,v);
        helper(root->right,v);
    }
    
    int isPairPresent(struct Node *root, int target)
    {
        if(root==NULL) return 0;
        vector<int> v;
        helper(root,v);
        
        sort(v.begin(),v.end());
        int i = 0;
        int j = v.size() - 1;
        
        int flag = 0;
        while(i<j){
            
            if(v[i] + v[j] == target){
                flag = 1;
                break;
            }else if(v[i] + v[j] > target){
                j--;
            }else{
                i++;
            }
        }
        
        if(flag) return 1;
        else return 0;
    }
};
+1
binnukaniki1232 months ago
class Solution{   // root : the root Node of the given BST   // target : the target sum   HashMap<Integer, Integer> hm           = new HashMap<Integer, Integer>();           int c=0;int ta;   public int isPairPresent(Node root, int target)   {       // Write your code here         ta=target;         inorder(root);       return c;   }   public void inorder(Node root){       if(root==null || c==1)return;       if(root.data<ta){           int p=ta-root.data;           if(hm.containsKey(p)){                             c=1;return;           }            hm.put(root.data,1);       }       inorder(root.left);       inorder(root.right);   }}
+2
sainikcodefreak2 months ago
class Solution{ public:   // root : the root Node of the given BST   // target : the target sum   unordered_set<int>s;   int isPairPresent(struct Node *root, int target)   {   //add code here.   if(root==NULL)   {       return 0;   }         if(s.count(target-root->data))       {           return 1;       }   else   {       s.insert(root->data);   }   return isPairPresent(root->left,target)|| isPairPresent(root->right,target);   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.