Skip to content

Commit bc88ad2

Browse files
committed
Leetocde 270 Closest Binary Search Tree Value
1 parent e11c362 commit bc88ad2

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed
Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
11
class Solution {
22
public int closestValue(TreeNode root, double target) {
3-
int ans = Integer.MAX_VALUE;
4-
double closest = Double.MAX_VALUE;
3+
double v = Double.MAX_VALUE;
4+
int ans = 0;
55
TreeNode p = root;
66
while(p != null) {
7-
if(Math.abs(target - p.val) < closest) {
7+
double nodeValue = p.val;
8+
if(Math.abs(nodeValue - target) == v) {
9+
ans = Math.min(p.val, ans);
10+
}else if(Math.abs(nodeValue - target) < v) {
811
ans = p.val;
9-
closest = Math.abs(target - p.val);
12+
v = Math.abs(nodeValue - target);
1013
}
11-
12-
if(p.val >= target){
14+
if(nodeValue >= target) {
1315
p = p.left;
14-
}else{
16+
}else {
1517
p = p.right;
1618
}
1719
}
18-
1920
return ans;
2021
}
2122
}

0270_Closest Binary Search Tree Value/ClosestBinarySearchTreeValue2.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ public int closestValue(TreeNode root, double target) {
88

99
private void traverse(TreeNode node, double target) {
1010
if(node == null) return;
11-
if(Math.abs(node.val - target) < v) {
11+
if(Math.abs(node.val - target) == v) {
12+
ans = Math.min(ans, node.val);
13+
}else if(Math.abs(node.val - target) < v) {
1214
ans = node.val;
1315
v = Math.abs(node.val - target);
1416
}

0 commit comments

Comments
 (0)