-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathClosestBinaryTreeSearchValue.java
More file actions
36 lines (30 loc) · 1008 Bytes
/
ClosestBinaryTreeSearchValue.java
File metadata and controls
36 lines (30 loc) · 1008 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
// https://leetcode.com/problems/closest-binary-search-tree-value
// T: O(logN)
// S: O(logN)
public class ClosestBinaryTreeSearchValue {
private static int result = Integer.MAX_VALUE;
public int closestValue(TreeNode root, double target) {
result = Integer.MAX_VALUE;
computeClosestValue(root, target);
return result;
}
private static void computeClosestValue(TreeNode root, double target) {
if (root == null) {
return;
}
if (root.val == target) {
result = root.val;
return;
}
if (Math.abs(root.val - target) == Math.abs(result - target) && root.val < result) {
result = root.val;
} else if (Math.abs(root.val - target) < Math.abs(result - target)) {
result = root.val;
}
if (root.val < target) {
computeClosestValue(root.right, target);
} else {
computeClosestValue(root.left, target);
}
}
}