leetcode270. 最接近的二叉搜索树值
生活随笔
收集整理的這篇文章主要介紹了
leetcode270. 最接近的二叉搜索树值
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)不為空的二叉搜索樹和一個(gè)目標(biāo)值 target,請(qǐng)?jiān)谠摱嫠阉鳂渲姓业阶罱咏繕?biāo)值 target 的數(shù)值。
注意:
給定的目標(biāo)值 target 是一個(gè)浮點(diǎn)數(shù)
題目保證在該二叉搜索樹中只會(huì)存在一個(gè)最接近目標(biāo)值的數(shù)
示例:
輸入: root = [4,2,5,1,3],目標(biāo)值 target = 3.714286
? ? 4
? ?/ \
? 2 ? 5
?/ \
1 ? 3
輸出: 4
思路:二分,當(dāng)前節(jié)點(diǎn)比target大就往左邊搜(因?yàn)橛疫叺牟罹喔?#xff09;,當(dāng)前節(jié)點(diǎn)比target小就往右搜(因?yàn)樽筮叺牟罹喔?#xff09;。
/*** 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) {int val, closest = root.val;while (root != null) {val = root.val;closest = Math.abs(val - target) < Math.abs(closest - target) ? val : closest;root = target < root.val ? root.left : root.right;}return closest;} }?
總結(jié)
以上是生活随笔為你收集整理的leetcode270. 最接近的二叉搜索树值的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。