[leetcode]270. Closest Binary Search Tree Value二叉搜索树中找target的最接近值


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;
}
}
上一篇:十三:SpringBoot-基于Yml配置方式,实现文件上传逻辑


下一篇:C++编程练习(10)----“图的最小生成树“(Prim算法、Kruskal算法)