forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClosestBinarySearchTreeValue.swift
47 lines (42 loc) · 1.4 KB
/
ClosestBinarySearchTreeValue.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Question Link: https://leetcode.com/problems/closest-binary-search-tree-value/
* Primary idea: Binary Search, update closest value, and choose to go left or right depends on
* the comparation between node.val and target
*
* Note: different data types of vars cannot operate together, e.g. Int and Double
* Time Complexity: O(logn), Space Complexity: O(1)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class ClosestBinarySearchTreeValue {
func closestValue(root: TreeNode?, _ target: Double) -> Int {
guard let root = root else {
return Int(target)
}
return _helper(root, target, root.val)
}
private func _helper(node: TreeNode?, _ target: Double, _ closest: Int) -> Int {
guard let node = node else {
return closest
}
var closest = closest
if abs(target - Double(node.val)) < abs(target - Double(closest)) {
closest = node.val
}
if Double(node.val) < target {
return _helper(node.right, target, closest)
} else {
return _helper(node.left, target, closest)
}
}
}