leetcode270. 最接近的二叉搜索树值
生活随笔
收集整理的這篇文章主要介紹了
leetcode270. 最接近的二叉搜索树值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個不為空的二叉搜索樹和一個目標值 target,請在該二叉搜索樹中找到最接近目標值 target 的數值。
注意:
給定的目標值 target 是一個浮點數
題目保證在該二叉搜索樹中只會存在一個最接近目標值的數
示例:
輸入: root = [4,2,5,1,3],目標值 target = 3.714286
? ? 4
? ?/ \
? 2 ? 5
?/ \
1 ? 3
輸出: 4
思路:二分,當前節點比target大就往左邊搜(因為右邊的差距更大),當前節點比target小就往右搜(因為左邊的差距更大)。
/*** 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;} }?
總結
以上是生活随笔為你收集整理的leetcode270. 最接近的二叉搜索树值的全部內容,希望文章能夠幫你解決所遇到的問題。