zoukankan      html  css  js  c++  java
  • [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

    代码

     1 class Solution {
     2     public int closestValue(TreeNode root, double target) {
     3         int result = root.val;   
     4         while(root != null){
     5             //update result if the current value is closer to target
     6             if(Math.abs(target - root.val) < Math.abs(target - result)){
     7                 result = root.val;
     8             }      
     9             //binary search
    10             root = root.val > target? root.left: root.right;
    11         }     
    12         return result;
    13     }
    14 }
  • 相关阅读:
    SpringMVC视图解析器
    JavaEE PO VO BO DTO POJO DAO 整理总结
    Android Studio JNI开发入门教程
    javah的使用
    右键“在此处打开命令行窗口”的一个小秘密
    URL和URI的区别
    自学使用
    Ribbon使用
    Eureka集群搭建
    ssm常见面试题
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9823968.html
Copyright © 2011-2022 走看看