-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClosestBinarySearchTreeValue.cc
More file actions
44 lines (37 loc) · 932 Bytes
/
Copy pathClosestBinarySearchTreeValue.cc
File metadata and controls
44 lines (37 loc) · 932 Bytes
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
44
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <math.h>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
double double_abs(double val){
return val > 0 ? val : -val;
}
class Solution {
public:
int closestValue(TreeNode* root, double target) {
if (!root) return INT_MAX;
if (!(root->left) && !(root->right)) return root->val;
int left = closestValue(root->left, target);
int right = closestValue(root->right, target);
double td = double_abs(root->val - target);
double ld = double_abs(left - target);
double rd = double_abs(right - target);
if (td < ld)
return td < rd ? root->val : right;
else
return ld < rd ? left : right;
}
};
int main(int argc, char const* argv[]) {
/* code */
return 0;
}