[LeetCode] Closest Nodes Queries in a Binary Search Tree

2476. Closest Nodes Queries in a Binary Search Tree

You are given the root of a binary search tree and an array queries of size n consisting of positive integers.

Find a 2D array answer of size n where answer[i] = [mini, maxi]:

  • mini is the largest value in the tree that is smaller than or equal to queries[i]. If a such value does not exist, add -1 instead.
  • maxi is the smallest value in the tree that is greater than or equal to queries[i]. If a such value does not exist, add -1 instead.

Return the array answer.

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
/**
* 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 {
void dfs(TreeNode* node, vector<int>& now) {
if(!node) return;
now.push_back(node->val);
dfs(node->left, now);
dfs(node->right, now);
}
public:
vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) {
vector<int> now;
dfs(root, now);
sort(begin(now), end(now));
now.erase(unique(begin(now),end(now)), end(now));
vector<vector<int>> res;
for(auto q : queries) {
auto lb = lower_bound(begin(now), end(now), q);
int mi = -1, ma = -1;
if(lb != end(now)) ma = *lb;
if(lb == end(now)) mi = *prev(lb);
else {
if(*lb == q) mi = *lb;
else if(lb != begin(now)) mi = *prev(lb);
}
res.push_back({mi,ma});
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/20/PS/LeetCode/closest-nodes-queries-in-a-binary-search-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.