-
Notifications
You must be signed in to change notification settings - Fork 4
/
1214. Two Sum BSTs.cpp
44 lines (41 loc) · 1.14 KB
/
1214. Two Sum BSTs.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 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 twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) {
unordered_map < int, bool > required;
queue <TreeNode* > q;
q.push(root1);
while(!q.empty()) {
TreeNode* currentNode = q.front();
required[target - currentNode->val] = true;
q.pop();
if(currentNode->left) {
q.push(currentNode->left);
}
if(currentNode->right) {
q.push(currentNode->right);
}
}
q.push(root2);
while(!q.empty()) {
TreeNode* currentNode = q.front();
if(required[currentNode->val] == true ) return true;
q.pop();
if(currentNode->left) {
q.push(currentNode->left);
}
if(currentNode->right) {
q.push(currentNode->right);
}
}
return false;
}
};