-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
38 lines (37 loc) · 1.04 KB
/
Solution.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
/**
* 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 twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) {
vector<int> vals1, vals2;
inorder(root1, vals1);
inorder(root2, vals2);
int i = 0, j = vals2.size() - 1;
while (i < vals1.size() && j >= 0) {
int s = vals1[i] + vals2[j];
if (s == target)
return true;
if (s < target)
++i;
else
--j;
}
return false;
}
void inorder(TreeNode* root, vector<int>& vals) {
if (root) {
inorder(root->left, vals);
vals.push_back(root->val);
inorder(root->right, vals);
}
}
};