forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClosestBinarySearchTreeValueII.swift
45 lines (40 loc) · 1.33 KB
/
ClosestBinarySearchTreeValueII.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
/**
* Question Link: Question Link: https://leetcode.com/problems/closest-binary-search-tree-value-ii/
* Primary idea: Inorder traverse, compare current node val with the first one of the
* array, as it is far from closest one as usual.
* Time Complexity: O(n), Space Complexity: O(n)
*
* 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 ClosestBinarySearchTreeValueII {
func closestKValues(_ root: TreeNode?, _ target: Double, _ k: Int) -> [Int] {
var res = [Int]()
inorder(root, target, k, &res)
return res
}
fileprivate func inorder(_ node: TreeNode?, _ target: Double, _ k: Int, _ res: inout [Int]) {
guard let node = node else {
return
}
inorder(node.left, target, k, &res)
if res.count < k {
res.append(node.val)
} else if abs(Double(res.first!) - target) > abs(Double(node.val) - target) {
res.removeFirst()
res.append(node.val)
} else {
return
}
inorder(node.right, target, k, &res)
}
}