-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathclosest_value_in_bst.cpp
43 lines (38 loc) · 972 Bytes
/
closest_value_in_bst.cpp
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
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the given BST
* @param target: the given target
* @return: the value in the BST that is closest to the target
*/
void helper(TreeNode *root, double target, int &closest) {
if(!root) return;
if(abs(root->val - target) < abs(closest - target)) {
closest = root->val;
}
if(root->val < target) {
helper(root->right, target, closest);
}
else {
helper(root->left, target, closest);
}
}
int closestValue(TreeNode * root, double target) {
// write your code here
int closest = -1;
helper(root, target, closest);
return closest;
}
};