270. Closest Binary Search Tree Value

270. Closest Binary Search Tree Value

Description

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest.

Example 1:

1
2
Input: root = [4,2,5,1,3], target = 3.714286
Output: 4

Example 2:

1
2
Input: root = [1], target = 4.428571
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [1, 10^4].
  • 0 <= Node.val <= 10^9
  • -10^9 <= target <= 10^9

Hints/Notes

  • 2024/02/15
  • bst
  • premium

Solution

Language: C++

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 {
public:
int res = INT_MAX;

int closestValue(TreeNode* root, double target) {
traverse(root, target);
return res;
}

void traverse(TreeNode* root, double target) {
if (!root) {
return;
}
if (root->val == target) {
res = root->val;
} else if (root->val > target) {
if (abs(root->val - target) < abs(res - target)) {
res = root->val;
}
traverse(root->left, target);
} else {
if (abs(root->val - target) <= abs(res - target)) {
res = root->val;
}
traverse(root->right, target);
}
}
};