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

题目链接:

题解

题目中有坑,如果树退化成一个链,每次在树上搜索会超时。所以先把二叉搜索树转到一个数组(中序遍历),然后每次在数组上二分查找。

参考代码

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
/*
* @lc app=leetcode.cn id=2476 lang=cpp
*
* [2476] 二叉搜索树最近节点查询
*/

// @lc code=start
/**
* 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:
vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) {
vector<int> tmp;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
TreeNode* node = q.front();
q.pop();
tmp.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}

sort(tmp.begin(), tmp.end());
vector<vector<int>> ans;
for(int i = 0; i < queries.size(); i++) {
int left = -1;
int right = -1;
int k = lower_bound(tmp.begin(), tmp.end(), queries[i]) - tmp.begin();
if(k!=tmp.size() && tmp[k] == queries[i]) {
left = queries[i];
right = queries[i];
}
else if (k == 0) {right = tmp[k];}
else if (k == tmp.size()) {left = tmp[k-1];}
else {
left = tmp[k-1];
right = tmp[k];
}


ans.push_back({left, right});
}
return ans;
}
};
// @lc code=end


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

https://blog.xiang578.com/problem/lc2476.html

作者

Ryen Xiang

发布于

2024-02-24

更新于

2024-04-20

许可协议


网络回响

评论