-
Notifications
You must be signed in to change notification settings - Fork 0
/
TwoSumIVInputisaBST
85 lines (69 loc) · 1.52 KB
/
TwoSumIVInputisaBST
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**************************************/
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
/***********************************/
class Solution {
public:
void inorderTraversal(TreeNode* root, vector<int> &nums)
{
if(root == NULL)
return;
inorderTraversal(root->left, nums);
nums.push_back(root->val);
inorderTraversal(root->right, nums);
}
bool findTarget(TreeNode* root, int k)
{
vector<int> nums;
inorderTraversal(root, nums);
int length = nums.size();
int p = 0;
int q = length - 1;
while(p < q)
{
if(nums[p] + nums[q] > k)
q--;
else if(nums[p] + nums[q] < k)
p++;
else
return true;
}
return false;
}
};
///////////////////////////////////
class Solution {
private:unordered_map<int, int> mp;
public:
bool findTarget(TreeNode* root, int k) {
if (root == NULL) return false;
return mapTool(root, k);
}
bool mapTool(TreeNode*root, int k) {
if (root == NULL) {
return false;
}
if (mp.count(k - root->val) ==1) {
return true;
}
mp[root->val] = root->val;
return (mapTool(root->left, k) || mapTool(root->right, k));
}
};