Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 Output: True
Example 2:
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 28 Output: False
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
unordered_set<int> st;
return insertIntoMap(root, st, k);
}
bool insertIntoMap(TreeNode* root, unordered_set<int>& st, int k){
if(!root){
return false;
}
if(st.count(k - root->val)){
return true;
}
st.insert(root->val);
return insertIntoMap(root->left, st, k) || insertIntoMap(root->right, st, k);
}
};
之前想了一个方法,首先遍历一遍二叉树,将所有节点插入到 unordered_set中,之后再遍历,如果
unordered_set中存在 k - root->val则返回true,
发现这样是不对的。比如二叉树[1] k = 2就不满足。所以需要在一边遍历的同时,将没有出现过的数值插入到unordered_set中,这样比较合理。