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
题目
给定一棵二叉搜索树和一个target,求出其节点中最接近该target的值。
思路
1. based on the BST's attribution ( left < root < right), we use binary search
代码
class Solution {
public int closestValue(TreeNode root, double target) {
int result = root.val;
while(root != null){
//update result if the current value is closer to target
if(Math.abs(target - root.val) < Math.abs(target - result)){
result = root.val;
}
//binary search
root = root.val > target? root.left: root.right;
}
return result;
}
}