在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. Note:
给定一个非空的二进制搜索树和一个目标值,在BST中查找最接近目标的值。 注:
Solution: 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 }
|
请发表评论