[LeetCode] Closest Binary Search Tree Value II

272. Closest Binary Search Tree Value II

Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return the answer in any order.

You are guaranteed to have only one unique set of k values in the BST that are closest to the target.

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
/**
* 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 travel(TreeNode* node, deque<int>& nums) {
if(!node) return;
travel(node->left, nums);
nums.push_back(node->val);
travel(node->right, nums);
}
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
deque<int> nums;
travel(root, nums);
while(nums.size() > k) {
if(abs(target - nums.front()) > abs(target - nums.back()))
nums.pop_front();
else
nums.pop_back();
}
return vector<int>(nums.begin(),nums.end());
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/11/PS/LeetCode/closest-binary-search-tree-value-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.