★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-gkgnnoon-kz.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.git
Note:github
給定一個非空的二進制搜索樹和一個目標值,在BST中查找最接近目標的值。 微信
注: spa
Solution:code
1 public class TreeNode { 2 public var val: Int 3 public var left: TreeNode? 4 public var right: TreeNode? 5 public init(_ val: Int) { 6 self.val = val 7 self.left = nil 8 self.right = nil 9 } 10 } 11 12 class Solution { 13 func closestValue(_ root: TreeNode?,_ target:Double) -> Int { 14 var a:Int = root!.val 15 var t:TreeNode? = target < Double(a) ? root?.left : root?.right 16 if t == nil {return a} 17 var b:Int = closestValue(t, target) 18 return abs(Double(a) - target) < abs(Double(b) - target) ? a : b 19 } 20 }