forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_270.java
100 lines (91 loc) · 3.25 KB
/
_270.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _270 {
public static class Solution1 {
//A general tree solution, this finished in 1 ms
public int closestValue(TreeNode root, double target) {
if (root == null) {
return 0;
}
double delta = Double.MAX_VALUE;
return dfs(root, target, delta, root.val);
}
private int dfs(TreeNode root, double target, double delta, int closestVal) {
if (Math.abs(root.val - target) < delta) {
closestVal = root.val;
delta = Math.abs(root.val - target);
}
int leftVal = closestVal;
if (root.left != null) {
leftVal = dfs(root.left, target, delta, closestVal);
}
int rightVal = closestVal;
if (root.right != null) {
rightVal = dfs(root.right, target, delta, closestVal);
}
return (Math.abs(leftVal - target) > Math.abs(rightVal - target)) ? rightVal : leftVal;
}
}
public static class Solution2 {
// BST solution
// we can tailor the solution to use the BST feature: left subtrees are always smaller than the root the right subtrees
//this finished in 0 ms
public int closestValue(TreeNode root, double target) {
if (root == null) {
return 0;
}
return dfs(root, target, root.val);
}
private int dfs(TreeNode root, double target, int minVal) {
if (root == null) {
return minVal;
}
if (Math.abs(root.val - target) < Math.abs(minVal - target)) {
minVal = root.val;
}
if (target < root.val) {
minVal = dfs(root.left, target, minVal);
} else {
minVal = dfs(root.right, target, minVal);
}
return minVal;
}
}
public static class Solution3 {
//a more concise solution
public int closestValue(TreeNode root, double target) {
if (root == null) {
return 0;
}
return dfs(root, target, root.val);
}
private int dfs(TreeNode root, double target, int minVal) {
if (root == null) {
return minVal;
}
if (Math.abs(root.val - target) < Math.abs(minVal - target)) {
minVal = root.val;
}
minVal = dfs(root.left, target, minVal);
minVal = dfs(root.right, target, minVal);
return minVal;
}
}
public static class Solution4 {
//BST iterative solution
public int closestValue(TreeNode root, double target) {
long minVal = Long.MAX_VALUE;
while (root != null) {
if (Math.abs(root.val - target) < Math.abs(minVal - target)) {
minVal = root.val;
}
if (target < root.val) {
root = root.left;
} else {
root = root.right;
}
}
return minVal == Long.MAX_VALUE ? 0 : (int) minVal;
}
}
}