[Swift]LeetCode270. Closest Binary Search Tree Value $ 最近的二分搜索树的值

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.

给定一个非空的二进制搜索树和一个目标值,在BST中查找最接近目标的值。 

注: 

  • 给定的目标值是一个浮点。
  • 您保证在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 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10648080.html
今日推荐