[Swift]LeetCode272. 最近的二分搜索樹的值 II $ Closest Binary Search Tree Value II

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-pakcjwaj-kz.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.node

Note:git

  • Given target value is a floating point.
  • You may assume k is always valid, that is: k ≤ total nodes.
  • You are guaranteed to have only one unique set of k values in the BST that are closest to the target.

Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?github

Hint:微信

1. Consider implement these two helper functions:
  i. getPredecessor(N), which returns the next smaller node to N.
  ii. getSuccessor(N), which returns the next larger node to N.
2. Try to assume that each node has a parent pointer, it makes the problem much easier.
3. Without parent pointer we just need to keep track of the path from the root to the current node using a stack.
4. You would need two stacks to track the path in finding predecessor and successor node separately.app


給定一個非空的二進制搜索樹和一個目標值,在BST中查找離目標最近的k值。less

注:ide

給定的目標值是一個浮點。函數

您能夠假定k始終有效,即:k≤總節點。spa

保證BST中只有一組最接近目標的惟一k值。

跟進:

假設BST是平衡的,您能夠在小於O(n)的運行時(其中n=總節點)中解決它嗎?

提示:

一、考慮實現這兩個助手函數:

  i.getPrevistory(n),它將下一個較小的節點返回到n。

  ii.getsuccessor(n),它將下一個較大的節點返回到n。

二、嘗試假設每一個節點都有一個父指針,這會使問題變得更容易。

三、若是沒有父指針,咱們只須要使用堆棧跟蹤從根到當前節點的路徑。

四、在單獨查找前置節點和後續節點時,須要兩個堆棧來跟蹤路徑。


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 closestKValues(_ root: TreeNode?,_ target:Double,_ k:Int) -> [Int] {
14         var res:[Int] = [Int]()
15         inorder(root, target, k, &res)
16         return res
17     }
18     
19     func inorder(_ root: TreeNode?,_ target:Double,_ k:Int,_ res:inout [Int])
20     {
21         if root == nil {return}
22         inorder(root?.left, target, k, &res)
23         if res.count < k
24         {
25             res.append(root!.val)
26         }
27         else if abs(Double(root!.val) - target) < abs(Double(res[0]) - target)
28         {
29             res.removeFirst()
30             res.append(root!.val)
31         }
32         else
33         {
34             return
35         }
36         inorder(root?.right, target, k, &res)
37     }
38 }
相關文章
相關標籤/搜索