成人无码视频,亚洲精品久久久久av无码,午夜精品久久久久久毛片,亚洲 中文字幕 日韩 无码

資訊專欄INFORMATION COLUMN

[LeetCode] 270. Closest Binary Search Tree Value

XUI / 2104人閱讀

Problem

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

Solution
class Solution {
    public int closestValue(TreeNode root, double target) {
        if (root == null) return -1;
        int res = root.val;
        while (root != null) {
            if (Math.abs(root.val-target) < Math.abs(res-target)) res = root.val;
            if (root.val > target) root = root.left;
            else root = root.right;
        }
        return res;
    }
}

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/72393.html

相關(guān)文章

  • LeetCode[270] Closest Binary Search Tree Value

    摘要:復(fù)雜度思路用一個(gè)變量來(lái)記錄當(dāng)前的值,并且在每次之前,比較得到目前的最大值。注意變量的比較不要用代碼 LeetCode[270] Closest Binary Search Tree Value Given a non-empty binary search tree and a target value, find the value in the BST that is close...

    pumpkin9 評(píng)論0 收藏0
  • [Leetcode] Closest Binary Search Tree Value 最近二叉搜索

    摘要:遞歸法復(fù)雜度時(shí)間空間思路根據(jù)二叉樹的性質(zhì),我們知道當(dāng)遍歷到某個(gè)根節(jié)點(diǎn)時(shí),最近的那個(gè)節(jié)點(diǎn)要么是在子樹里面,要么就是根節(jié)點(diǎn)本身。因?yàn)槲覀冎离x目標(biāo)數(shù)最接近的數(shù)肯定在二叉搜索的路徑上。 Closest Binary Search Tree Value I Given a non-empty binary search tree and a target value, find the va...

    AlphaWallet 評(píng)論0 收藏0
  • 272. Closest Binary Search Tree Value II

    摘要:題目鏈接的值大小順序?qū)嶋H上就是滿足的條件,所以直接中序遍歷,過(guò)程中維護(hù)一個(gè),放入個(gè)當(dāng)前離最近的值,的時(shí),新的值和的距離如果小于隊(duì)首的那個(gè)值和的距離那么移除隊(duì)首,如果,且新的距離大于等于隊(duì)首的距離,直接退出,返回隊(duì)列中的所有結(jié)果。 272. Closest Binary Search Tree Value II 題目鏈接:https://leetcode.com/problems... ...

    NusterCache 評(píng)論0 收藏0
  • LeetCode 272 Closest Binary Tree Traversal II 解題思路

    摘要:原題網(wǎng)址題意在二叉搜索樹當(dāng)中找到離最近的個(gè)數(shù)。解題思路由于二叉搜索數(shù)的中序遍歷是有序的,比如例子中的樹,中序遍歷為。 原題網(wǎng)址:https://leetcode.com/problems... Given a non-empty binary search tree and a target value, find?k?values in the BST that are closes...

    Youngdze 評(píng)論0 收藏0
  • [Leetcode - Tree] Binary Search Tree Iterator

    摘要:解題思路對(duì)于二叉搜索樹,我們很容易會(huì)想到使用棧和隊(duì)列來(lái)解決問(wèn)題,本題是要求實(shí)現(xiàn)一個(gè)對(duì)二叉搜索樹的遍歷器,要求每次可以返回最小的節(jié)點(diǎn)值,我們使用棧。 Binary Search Tree IteratorImplement an iterator over a binary search tree (BST). Your iterator will be initialized with...

    jsyzchen 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

閱讀需要支付1元查看
<