博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
270. Closest Binary Search Tree Value - Easy
阅读量:6914 次
发布时间:2019-06-27

本文共 994 字,大约阅读时间需要 3 分钟。

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   3Output: 4

 

binary search

time: O(h), space: O(1)  -- h: height of the tree

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public int closestValue(TreeNode root, double target) {        TreeNode node = root;        int min = root.val;        while(node != null) {            if(Math.abs(node.val - target) < Math.abs(min - target)) {                min = node.val;            }            node = node.val > target ? node.left : node.right;        }        return min;    }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10133073.html

你可能感兴趣的文章
csu 1984: LXX的能力值
查看>>
汉编随想(一)
查看>>
开源的Android开发框架-------PowerFramework使用心得(五)网络请求HTTPRequest
查看>>
[转载]kmeans
查看>>
一个不错的架构图:基于SpringCloud的微服务项目
查看>>
成为顶尖自由职业者必备的7个软技能之一:沟通(转)
查看>>
获取合并单元格中值的一个方法POI
查看>>
ORACLE Install (10g r2) FOR Red Hat Enterprise Linux Server release 5.5 (64 bit) (转)
查看>>
入手Invicta 8926 OB潜水自动机械腕表
查看>>
Android UI适配总结(一)寻找最佳匹配资源
查看>>
我是小白之<%%>用法
查看>>
F# 入门(十一):链表与数组
查看>>
树套树
查看>>
[IOS笔记] - 关于线程[3]
查看>>
java socket通信-传输文件图片--传输图片
查看>>
Windows 10 远程连接出现函数错误 【这可能由于CredSSP加密Oracle修正】
查看>>
MySQL read_only选项的作用
查看>>
职业方向
查看>>
3DMAX 卸载工具,完美彻底卸载清除干净3dmax各种残留注册表和文件
查看>>
生日蜡烛
查看>>