-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathClosestBinarySearchTreeValue.cpp
More file actions
33 lines (32 loc) · 1.09 KB
/
Copy pathClosestBinarySearchTreeValue.cpp
File metadata and controls
33 lines (32 loc) · 1.09 KB
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
// Problem: https://leetcode.com/problems/closest-binary-search-tree-value/
// 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 ClosestBinarySearchTreeValue {
public:
int closestValue(TreeNode* root, double target) {
double delta = abs(target - (double)root->val);
int clValue = root->val;
if (root->left != nullptr) {
int l = closestValue(root->left, target);
if (abs((double)l - target) < delta) {
clValue = l;
delta = abs((double)l - target);
}
}
if (root->right != nullptr) {
int r = closestValue(root->right, target);
if (abs((double)r - target) < delta) {
clValue = r;
delta = abs((double)r - target);
}
}
return clValue;
}
};