270. Closest-Binary-Search-Tree-Value
difficulty: Easy
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
Example:
Input: root = [4,2,5,1,3], target = 3.714286
4
/ \
2 5
/ \
1 3
Output: 4
Method One
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
TreeNode cur = root;
int closest = root.val;
while(cur != null) {
closest = Math.abs(target - cur.val) < Math.abs(target - closest) ? cur.val : closest;
if( target < cur.val ) {
cur = cur.left;
}else if( target > cur.val) {
cur = cur.right;
}else{
return cur.val;
}
}
return closest;
}
}
2023 写的 应该没看答案至少
class Solution {
public int closestValue(TreeNode root, double target) {
double min = Integer.MAX_VALUE + 0.1;
int minVal = 0;
TreeNode p = root;
while (p != null) {
if (min == Math.abs(p.val - target)) {
minVal = Math.min(minVal, p.val);
}
if (min > Math.abs(p.val - target)) {
min = Math.abs(p.val - target);
minVal = p.val;
}
if (p.val < target ) {
p = p.right;
} else {
p = p.left;
}
}
return minVal;
}
}
Last updated
Was this helpful?