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
思路:遍历二叉树,然后将元素放到数组中,然后利用查找
代码1:
/**
* 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) {
if(root==NULL){return false;}
queue<TreeNode*> s;
vector<int> tofind;
s.push(root);
while(!s.empty()){
TreeNode* node;
node = s.front();
s.pop();
if(node->left) {s.push(node->left);}
if(node->right) {s.push(node->right);}
//if(node->val == k){return true;}
//else{
if(find(tofind.begin(),tofind.end(),(node->val))==tofind.end()){
tofind.push_back(k-node->val);
}
else{return true;}
//}
}
return false;
}
};
代码2:
/**
* 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) {
if(!root){return false;}
queue<TreeNode*> p;
vector<int> res;
p.push(root);
while(!p.empty()){
TreeNode* temp=p.front();
p.pop();
res.push_back(temp->val);
if(temp->left!=NULL){p.push(temp->left);}
if(temp->right!=NULL){p.push(temp->right);}
}
for(int i=0;i<res.size()-1;i++){
if(find(res.begin()+i+1,res.end(),k-res[i])!=res.end()){return true;}
}
return false;
}
};
代码3:
/**
* 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> set;
return dfs(root, set, k);
}
bool dfs(TreeNode* root, unordered_set<int>& set, int k){
if(root == NULL)return false;
if(set.count(k - root->val))return true;
set.insert(root->val);
return dfs(root->left, set, k) || dfs(root->right, set, k);
}
};