forked from armankhondker/leetcode-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
closestBinarySearchTreeValue.java
58 lines (48 loc) · 1.62 KB
/
closestBinarySearchTreeValue.java
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
57
58
// Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
//BEST APPROACH - USE BINARY SEARCH!!
//TC: O(logN)=====O(H) since it goes down a path from root to leaf
//SC: O(1) constant space
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
int closestVal = root.val;
while(root != null){
//update closestVal if the current value is closer to target
closestVal = (Math.abs(target - root.val) < Math.abs(target - closestVal))? root.val : closestVal;
if(closestVal == target){ //already find the best result
return closestVal;
}
root = (root.val > target)? root.left: root.right; //binary search
}
return closestVal;
}
}
//RECURSIVE Solution - NOT AS GOOD
//TC: O(N) to search all nodes
//SC: O(N) to keep in order traversal
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;
}
});
}
}