给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。
案例 1:
输入:5/ \3 6/ \ \2 4 7Target = 9输出: True
 
案例 2:
输入: 
    5
   / \
  3   6
 / \   \
2   4   7
Target = 28
输出: False
/**
 * 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:
    unordered_map<int, int> hashMap;
    bool findTarget(TreeNode* root, int k) {
        dfs(root);
        unordered_map<int, int>::iterator it;
        cout<<hashMap.size()<<endl;
        for(it = hashMap.begin(); it != hashMap.end(); it++){
            if(k - it->first != it->first && hashMap.count(k - it->first)){
                return true;
            }else if(k - it->first == it->first && hashMap[it->first] > 1){
                return true;
            }
        }
        return false;
    }
    void dfs(TreeNode* root){
        if(root == nullptr) return;
        hashMap[root->val]++;
        dfs(root->left);
        dfs(root->right);
        return ;
    }
};
                    