forked from dishanp/Algorithms-For-Software-Developers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2 sum - BST.cpp
29 lines (28 loc) · 857 Bytes
/
2 sum - BST.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 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) {
unordered_set<int> elements;
return findSum(root,k,elements);
}
bool findSum(TreeNode* root,int k,unordered_set<int>& elements){ //9
if(root==NULL){
return false;
}
if(elements.count(k-root->val)){
return true;
}
elements.insert(root->val);
return findSum(root->left,k,elements) || findSum(root->right,k,elements);
}
};