forked from terrytong0876/LintCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClosest Binary Search Tree Value.java
More file actions
56 lines (49 loc) · 1.25 KB
/
Copy pathClosest Binary Search Tree Value.java
File metadata and controls
56 lines (49 loc) · 1.25 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
E
Binary Search. 记录找到过的closest. 直到tree leaf, 找完return
```
/*
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
Tags: Tree Binary Search
Similar Problems: (M) Count Complete Tree Nodes, (H) Closest Binary Search Tree Value II
*/
/*
Thoughts:
Binary search, maintain a closest value.
Note: initial closest in real case is just the root, since we start from the root
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
if (root == null) {
return 0;
}
double closest = root.val;
while (root != null) {
if (root.val == target) {
return root.val;
} else {
if (Math.abs(target - closest) >= Math.abs(target - root.val)) {
closest = root.val;
}
if (root.val > target) {
root = root.left;
} else {
root = root.right;
}
}
}//END while
return (int)closest;
}
}
```