-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_2476_closestNodes.cc
128 lines (120 loc) · 2.38 KB
/
Problem_2476_closestNodes.cc
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <functional>
#include <vector>
using namespace std;
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:
vector<int> f(TreeNode* root, int x)
{
if (root == nullptr)
{
return {-1, -1};
}
int L = -1, R = -1;
TreeNode* cur = root;
while (cur != nullptr)
{
if (cur->val < x)
{
L = cur->val;
cur = cur->right;
}
else if (cur->val > x)
{
R = cur->val;
cur = cur->left;
}
else
{
L = cur->val;
R = cur->val;
break;
}
}
return {L, R};
}
// 递归解法部分用例超时,题设条件的二叉搜索树不一定是平衡的,存在极端情况时间复杂度为O(N)
vector<vector<int>> closestNodes1(TreeNode* root, vector<int>& queries)
{
vector<vector<int>> ans;
for (auto& x : queries)
{
vector<int> interval = f(root, x);
ans.push_back(std::move(interval));
}
return ans;
}
// 中序遍历然后二分查找,时间复杂度O(logN)
vector<vector<int>> closestNodes2(TreeNode* root, vector<int>& queries)
{
vector<int> tree;
function<void(TreeNode*)> dfs = [&](TreeNode* cur)
{
if (cur == nullptr)
{
return;
}
dfs(cur->left);
tree.push_back(cur->val);
dfs(cur->right);
};
dfs(root);
vector<vector<int>> ans;
for (int x : queries)
{
int left = nearLeft(tree, x);
int right = nearRight(tree, x);
ans.push_back({left, right});
}
return ans;
}
int nearLeft(vector<int>& arr, int x)
{
int L = 0;
int R = arr.size() - 1;
int ans = -1;
while (L <= R)
{
int M = (R - L) / 2 + L;
if (arr[M] <= x)
{
ans = arr[M];
L = M + 1;
}
else
{
R = M - 1;
}
}
return ans;
}
int nearRight(vector<int>& arr, int x)
{
int L = 0;
int R = arr.size() - 1;
int ans = -1;
while (L <= R)
{
int M = (R - L) / 2 + L;
if (x <= arr[M])
{
ans = arr[M];
R = M - 1;
}
else
{
L = M + 1;
}
}
return ans;
}
};