Problem Statement

Given the root of a Binary Search Tree and a target number k, return *true if there exist two elements in the BST such that their sum is equal to the given target*.

Example 1:

Input: root = [5,3,6,2,4,null,7], k = 9
Output: true

Problem Link

Two Sum IV - Input is a BST - LeetCode

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        
        if(!root)
            return false;
        
        if(!root->left && !root->right)
            return false;
        
        unordered_set<int> s;
        Insert(root,s);
        return solve(root,k,s);
        
    }
    void Insert(TreeNode* root,unordered_set<int>& s)
    {
        if(!root)
            return ;
        
      
            s.insert(root->val);
        
       
        Insert(root->left,s);
        Insert(root->right,s);
        
        
    }
    
    bool solve(TreeNode* root,int k,unordered_set<int>& s)
    {
        if(!root)
            return false;
        
        if(k!=2*root->val&&s.find(k-root->val)!=s.end())
            return true;
        
         return solve(root->left,k,s) || solve(root->right,k,s);
    }
};