Day114 | 灵神 | 二叉树 | 二叉搜索树的最小绝对差

2476.二叉搜索树最近节点查询

2476. 二叉搜索树最近节点查询 - 力扣(LeetCode)

思路:

这道题目拿到手就觉得在树中递归查找太费劲了,还是转化为有序数组在数组中使用二分比较方便

1.中序遍历root得到有序数组arr

2.二分查找queries[i]即可找到最大最小值

C++ 中 lower_bound 与 upper_bound 函数详解-CSDN博客

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
class Solution {
public:
vector<int> arr;
//1.得到有序数组
void tra(TreeNode *t)
{
if(t==nullptr)
return ;
tra(t->left);
arr.push_back(t->val);
tra(t->right);
}
vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) {
tra(root);
vector<vector<int>> res;
for(int i=0;i<queries.size();i++)
{
int maxVal = -1, minVal = -1;
//2.二分查找queries[i]
auto it = lower_bound(arr.begin(), arr.end(), queries[i]);
//找到了it,是第一个不小于queries[i]的数
if (it != arr.end()) {
maxVal = *it;
//如果相等,那么最大最小值都是it
if (*it == queries[i]) {
minVal = *it;
res.push_back({minVal, maxVal});
continue;
}
}
//如果it和queries[i]不相等 最小值就是it的前一个元素即--it,不等于begin是为了防止迭代器越界
if (it != arr.begin()) {
minVal = *(--it);
}
res.push_back({minVal, maxVal});
}
return res;
}
};