-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPremium-2 Closest Binary Search Tree Value
More file actions
53 lines (47 loc) · 1.39 KB
/
Premium-2 Closest Binary Search Tree Value
File metadata and controls
53 lines (47 loc) · 1.39 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
class Solution {
public void inorder(TreeNode root, List<Integer> nums) {
if (root == null) return;
inorder(root.left, nums);
nums.add(root.val);
inorder(root.right, nums);
}
public int closestValue(TreeNode root, double target) {
List<Integer> nums = new ArrayList();
inorder(root, nums);
return Collections.min(nums, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Math.abs(o1 - target) < Math.abs(o2 - target) ? -1 : 1;
}
});
}
}
class Solution {
public int closestValue(TreeNode root, double target) {
LinkedList<TreeNode> stack = new LinkedList();
long pred = Long.MIN_VALUE;
while (!stack.isEmpty() || root != null) {
while (root != null) {
stack.add(root);
root = root.left;
}
root = stack.removeLast();
if (pred <= target && target < root.val)
return Math.abs(pred - target) < Math.abs(root.val - target) ? (int)pred : root.val;
pred = root.val;
root = root.right;
}
return (int)pred;
}
}
class Solution {
public int closestValue(TreeNode root, double target) {
int val, closest = root.val;
while (root != null) {
val = root.val;
closest = Math.abs(val - target) < Math.abs(closest - target) ? val : closest;
root = target < root.val ? root.left : root.right;
}
return closest;
}
}