900. 二叉搜索树中最接近的值  

900. 二叉搜索树中最接近的值

  给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值

样例

样例1 输入: root = {5,4,9,2,#,8,10} and target = 6.124780 输出: 5 解释: 二叉树 {5,4,9,2,#,8,10},表示如下的树结构: 5 / \ 4 9 / / \ 2 8 10 样例2 输入: root = {3,2,4,1} and target = 4.142857 输出: 4 解释: 二叉树 {3,2,4,1},表示如下的树结构: 3 / \ 2 4 / 1

注意事项

  • 给出的目标值为浮点数
  • 我们可以保证只有唯一一个最接近给定值的节点
  public class Solution {     /**      * @param root:   the given BST      * @param target: the given target      * @return: the value in the BST that is closest to the target      */     public int closestValue(TreeNode root, double target) {         // write your code here         getValue(root, target);         return ret;     }         int ret = 0;     double min = Integer.MAX_VALUE;         private void getValue(TreeNode root, double target) {         if (root == null) return;         if (root.val < target) {             double temp = target - root.val;             if (temp < min) {                 ret = root.val;                 min = temp;             }             if (min < 0.5) {                 return;             }             getValue(root.right, target);         } else {             double temp = root.val - target;             if (temp < min) {                 ret = root.val;                 min = temp;             }             if (min < 0.5) {                 return;             }             getValue(root.left, target);         }     } }  
上一篇:单片机应用案例大全-900套(保持更新)


下一篇:【Golang】Golang 入门 : 切片(slice)