Skip to content

Commit e57910c

Browse files
solves #270: Closes binary search tree value in java
1 parent 6c3753f commit e57910c

File tree

3 files changed

+37
-5
lines changed

3 files changed

+37
-5
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@
235235
| 267 | 🔒 [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii) | | |
236236
| 268 | [Missing Number](https://leetcode.com/problems/missing-number) | [![Java](assets/java.png)](src/MissingNumber.java) [![Python](assets/python.png)](python/missing_number.py) | |
237237
| 269 | [Alien Dictionary](https://leetcode.com/problems/alien-dictionary) | [![Java](assets/java.png)](src/AlienDictionary.java) | |
238-
| 270 | 🔒 [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value) | | |
238+
| 270 | 🔒 [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value) | [![Java](assets/java.png)](src/ClosestBinaryTreeSearchValue.java) | |
239239
| 271 | 🔒 [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings) | | |
240240
| 274 | [H-Index](https://leetcode.com/problems/h-index) | [![Java](assets/java.png)](src/HIndex.java) | |
241241
| 275 | [H-Index II](https://leetcode.com/problems/h-index-ii) | [![Java](assets/java.png)](src/HIndexII.java) | |

src/ClosestBinaryTreeSearchValue.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// https://leetcode.com/problems/closest-binary-search-tree-value
2+
// T: O(logN)
3+
// S: O(logN)
4+
5+
public class ClosestBinaryTreeSearchValue {
6+
private static int result = Integer.MAX_VALUE;
7+
8+
public int closestValue(TreeNode root, double target) {
9+
result = Integer.MAX_VALUE;
10+
computeClosestValue(root, target);
11+
return result;
12+
}
13+
14+
private static void computeClosestValue(TreeNode root, double target) {
15+
if (root == null) {
16+
return;
17+
}
18+
19+
if (root.val == target) {
20+
result = root.val;
21+
return;
22+
}
23+
24+
if (Math.abs(root.val - target) == Math.abs(result - target) && root.val < result) {
25+
result = root.val;
26+
} else if (Math.abs(root.val - target) < Math.abs(result - target)) {
27+
result = root.val;
28+
}
29+
30+
if (root.val < target) {
31+
computeClosestValue(root.right, target);
32+
} else {
33+
computeClosestValue(root.left, target);
34+
}
35+
}
36+
}

src/FindKClosestElements.java

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,4 @@ private static int binarySearch(int[] array, int x) {
3838
}
3939
return left;
4040
}
41-
42-
public static void main(String[] args) {
43-
System.out.println(findClosestElements(new int[] {}, 3, 5));
44-
}
4541
}

0 commit comments

Comments
 (0)