-
Notifications
You must be signed in to change notification settings - Fork 0
/
2476. 二叉搜索树最近节点查询.cpp
63 lines (61 loc) · 1.57 KB
/
2476. 二叉搜索树最近节点查询.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* 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:
int getclosetsmallest(vector<int>&temp,int curr){
int ans=-1;
int start=0;
int end=temp.size()-1;
while(start<=end){
int mid=start+(end-start)/2;
if(temp[mid]>curr){
end=mid-1;
}else{
ans=temp[mid];
start=mid+1;
}
}
return ans;
}
int getclosetlargest(vector<int>&temp,int curr){
int ans=-1;
int start=0;
int end=temp.size()-1;
while(start<=end){
int mid=start+(end-start)/2;
if(temp[mid]>=curr){
ans=temp[mid];
end=mid-1;
}else{
start=mid+1;
}
}
return ans;
}
void solve(vector<int>&temp,TreeNode* root){
if(root==NULL) return ;
solve(temp,root->left);
temp.push_back(root->val);
solve(temp,root->right);
}
vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) {
vector<vector<int>>ans;
vector<int>temp;
solve(temp,root);
for(int i=0;i<queries.size();i++){
int small=getclosetsmallest(temp,queries[i]);
int largest=getclosetlargest(temp,queries[i]);
ans.push_back({small,largest});
}
return ans;
}
};