forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
47 lines (42 loc) · 913 Bytes
/
main.cpp
File metadata and controls
47 lines (42 loc) · 913 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
45
46
47
#include <cstdlib>
#include <iostream>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class TreeNode {
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) { val = x; left = nullptr; right = nullptr;}
};
class Solution {
public:
int closestValue(TreeNode* root, double target) {
int ret = root->val;
while(root != nullptr){
//update ret if the current value is closer to target
ret = abs(target - root->val) < abs(target - ret)
? root->val
: ret;
//binary search
root = root->val > target
? root->left
: root->right;
}
return ret;
}
};
int main() {
Solution sol;
TreeNode e(2);
e.left = new TreeNode(1);
e.right = new TreeNode(4);
cout << sol.closestValue(&e, 1.7) << endl;
return 0;
}