@@ -12,8 +12,9 @@ public class _270 {
12
12
class GeneralTreeSolution {
13
13
//this finished in 1 ms
14
14
public int closestValue (TreeNode root , double target ) {
15
- if (root == null )
15
+ if (root == null ) {
16
16
return 0 ;
17
+ }
17
18
double delta = Double .MAX_VALUE ;
18
19
return dfs (root , target , delta , root .val );
19
20
}
@@ -24,11 +25,13 @@ private int dfs(TreeNode root, double target, double delta, int closestVal) {
24
25
delta = Math .abs (root .val - target );
25
26
}
26
27
int leftVal = closestVal ;
27
- if (root .left != null )
28
+ if (root .left != null ) {
28
29
leftVal = dfs (root .left , target , delta , closestVal );
30
+ }
29
31
int rightVal = closestVal ;
30
- if (root .right != null )
32
+ if (root .right != null ) {
31
33
rightVal = dfs (root .right , target , delta , closestVal );
34
+ }
32
35
return (Math .abs (leftVal - target ) > Math .abs (rightVal - target )) ? rightVal : leftVal ;
33
36
}
34
37
}
@@ -37,12 +40,16 @@ class BSTSolutionRecursive {
37
40
//we can tailor the solution to use the BST feature: left subtrees are always smaller than the root the right subtrees
38
41
//this finished in 0 ms
39
42
public int closestValue (TreeNode root , double target ) {
40
- if (root == null ) return 0 ;
43
+ if (root == null ) {
44
+ return 0 ;
45
+ }
41
46
return dfs (root , target , root .val );
42
47
}
43
48
44
49
private int dfs (TreeNode root , double target , int minVal ) {
45
- if (root == null ) return minVal ;
50
+ if (root == null ) {
51
+ return minVal ;
52
+ }
46
53
if (Math .abs (root .val - target ) < Math .abs (minVal - target )) {
47
54
minVal = root .val ;
48
55
}
@@ -57,13 +64,16 @@ private int dfs(TreeNode root, double target, int minVal) {
57
64
58
65
class GeneralTreeSolutionMoreConcise {
59
66
public int closestValue (TreeNode root , double target ) {
60
- if (root == null ) return 0 ;
67
+ if (root == null ) {
68
+ return 0 ;
69
+ }
61
70
return dfs (root , target , root .val );
62
71
}
63
72
64
73
private int dfs (TreeNode root , double target , int minVal ) {
65
- if (root == null )
74
+ if (root == null ) {
66
75
return minVal ;
76
+ }
67
77
if (Math .abs (root .val - target ) < Math .abs (minVal - target )) {
68
78
minVal = root .val ;
69
79
}
@@ -80,8 +90,11 @@ public int closestValue(TreeNode root, double target) {
80
90
if (Math .abs (root .val - target ) < Math .abs (minVal - target )) {
81
91
minVal = root .val ;
82
92
}
83
- if (target < root .val ) root = root .left ;
84
- else root = root .right ;
93
+ if (target < root .val ) {
94
+ root = root .left ;
95
+ } else {
96
+ root = root .right ;
97
+ }
85
98
}
86
99
return minVal == Long .MAX_VALUE ? 0 : (int ) minVal ;
87
100
}
0 commit comments