原题链接在这里:https://leetcode.com/problems/closest-binary-search-tree-value/
题目:
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
题解:
target 一定在找的path 上,若是出现了比minDiff 还小的 差值,就把改点更新为cloest.
但注意target 是 double, 会有溢出情况,所以minDiff 初始化成Double.MAX_VALUE.
Time Complexity: O(h). h 是树的高度. Space: O(1).
AC Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
if(root == null){
return -1;
} int cloest = root.val;
double minDiff = Double.MAX_VALUE; while(root != null){
if(Math.abs(root.val - target) < minDiff){
minDiff = Math.abs(root.val - target);
cloest = root.val;
}
if(target > root.val){
root = root.right;
}else if(target < root.val){
root = root.left;
}else{
return root.val;
}
}
return cloest;
}
}