2
2
3
3
import com .fishercoder .common .classes .TreeNode ;
4
4
5
- /**Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
6
-
7
- Note:
8
- Given target value is a floating point.
9
- You are guaranteed to have only one unique value in the BST that is closest to the target.*/
10
5
public class _270 {
11
6
12
- class GeneralTreeSolution {
13
- //this finished in 1 ms
7
+ public static class Solution1 {
8
+ //A general tree solution, this finished in 1 ms
14
9
public int closestValue (TreeNode root , double target ) {
15
10
if (root == null ) {
16
11
return 0 ;
@@ -36,8 +31,9 @@ private int dfs(TreeNode root, double target, double delta, int closestVal) {
36
31
}
37
32
}
38
33
39
- class BSTSolutionRecursive {
40
- //we can tailor the solution to use the BST feature: left subtrees are always smaller than the root the right subtrees
34
+ public static class Solution2 {
35
+ // BST solution
36
+ // we can tailor the solution to use the BST feature: left subtrees are always smaller than the root the right subtrees
41
37
//this finished in 0 ms
42
38
public int closestValue (TreeNode root , double target ) {
43
39
if (root == null ) {
@@ -62,7 +58,8 @@ private int dfs(TreeNode root, double target, int minVal) {
62
58
}
63
59
}
64
60
65
- class GeneralTreeSolutionMoreConcise {
61
+ public static class Solution3 {
62
+ //a more concise solution
66
63
public int closestValue (TreeNode root , double target ) {
67
64
if (root == null ) {
68
65
return 0 ;
@@ -83,7 +80,8 @@ private int dfs(TreeNode root, double target, int minVal) {
83
80
}
84
81
}
85
82
86
- class BSTSolutionIterative {
83
+ public static class Solution4 {
84
+ //BST iterative solution
87
85
public int closestValue (TreeNode root , double target ) {
88
86
long minVal = Long .MAX_VALUE ;
89
87
while (root != null ) {
0 commit comments