[LeetCode] Closest Binary Search Tree Value

270. Closest Binary Search Tree Value

Given the root of a binary search tree and a target value, return the value in the BST that is 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
/**
* 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 {
double diff = DBL_MAX;
int res = 0;
void helper(TreeNode* n, double t) {
if(!n) return;
if(abs(n->val - t) < diff) {
diff = abs(n->val - t);
res = n->val;
}

helper(n->left,t);
helper(n->right,t);
}
public:
int closestValue(TreeNode* root, double target) {
helper(root,target);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/05/PS/LeetCode/closest-binary-search-tree-value/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.