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

Note:

  • 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)?

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.

270. Closest Binary Search Tree Value 的拓展,270题只要找出离目标值最近的一个节点值,而这道题要找出离目标值最近的k个节点值。

解法1:Brute Force, 中序遍历或者其它遍历,同时维护一个大小为k的max heap。

Java:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<Integer> closestKValues(TreeNode root, double target, int k) {
  12. LinkedList<Integer> res = new LinkedList<>();
  13. inOrderTraversal(root, target, k, res);
  14. return res;
  15. }
  16.  
  17. private void inOrderTraversal(TreeNode root, double target, int k, LinkedList<Integer> res) {
  18. if (root == null) {
  19. return;
  20. }
  21. inOrderTraversal(root.left, target, k, res);
  22. if (res.size() < k) {
  23. res.add(root.val);
  24. } else if(res.size() == k) {
  25. if (Math.abs(res.getFirst() - target) > (Math.abs(root.val - target))) {
  26. res.removeFirst();
  27. res.addLast(root.val);
  28. } else {
  29. return;
  30. }
  31. }
  32. inOrderTraversal(root.right, target, k, res);
  33. }
  34. }

Java:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. private PriorityQueue<Integer> minPQ;
  12. private int count = 0;
  13. public List<Integer> closestKValues(TreeNode root, double target, int k) {
  14. minPQ = new PriorityQueue<Integer>(k);
  15. List<Integer> result = new ArrayList<Integer>();
  16.  
  17. inorderTraverse(root, target, k);
  18.  
  19. // Dump the pq into result list
  20. for (Integer elem : minPQ) {
  21. result.add(elem);
  22. }
  23.  
  24. return result;
  25. }
  26.  
  27. private void inorderTraverse(TreeNode root, double target, int k) {
  28. if (root == null) {
  29. return;
  30. }
  31.  
  32. inorderTraverse(root.left, target, k);
  33.  
  34. if (count < k) {
  35. minPQ.offer(root.val);
  36. } else {
  37. if (Math.abs((double) root.val - target) < Math.abs((double) minPQ.peek() - target)) {
  38. minPQ.poll();
  39. minPQ.offer(root.val);
  40. }
  41. }
  42. count++;
  43.  
  44. inorderTraverse(root.right, target, k);
  45. }
  46. } 

Java:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11.  
  12. public List<Integer> closestKValues(TreeNode root, double target, int k) {
  13. PriorityQueue<Double> maxHeap = new PriorityQueue<Double>(k, new Comparator<Double>() {
  14. @Override
  15. public int compare(Double x, Double y) {
  16. return (int)(y-x);
  17. }
  18. });
  19. Set<Integer> set = new HashSet<Integer>();
  20.  
  21. rec(root, target, k, maxHeap, set);
  22.  
  23. return new ArrayList<Integer>(set);
  24. }
  25.  
  26. private void rec(TreeNode root, double target, int k, PriorityQueue<Double> maxHeap, Set<Integer> set) {
  27. if(root==null) return;
  28. double diff = Math.abs(root.val-target);
  29. if(maxHeap.size()<k) {
  30. maxHeap.offer(diff);
  31. set.add(root.val);
  32. } else if( diff < maxHeap.peek() ) {
  33. double x = maxHeap.poll();
  34. if(! set.remove((int)(target+x))) set.remove((int)(target-x));
  35. maxHeap.offer(diff);
  36. set.add(root.val);
  37. } else {
  38. if(root.val > target) rec(root.left, target, k, maxHeap,set);
  39. else rec(root.right, target, k, maxHeap, set);
  40. return;
  41. }
  42. rec(root.left, target, k, maxHeap, set);
  43. rec(root.right, target, k, maxHeap, set);
  44. }
  45. }

Java: A time linear solution, The time complexity would be O(k + (n - k) logk). Space complexity is O(k).

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<Integer> closestKValues(TreeNode root, double target, int k) {
  12. List<Integer> result = new ArrayList<>();
  13. if (root == null) {
  14. return result;
  15. }
  16.  
  17. Stack<Integer> precedessor = new Stack<>();
  18. Stack<Integer> successor = new Stack<>();
  19.  
  20. getPredecessor(root, target, precedessor);
  21. getSuccessor(root, target, successor);
  22.  
  23. for (int i = 0; i < k; i++) {
  24. if (precedessor.isEmpty()) {
  25. result.add(successor.pop());
  26. } else if (successor.isEmpty()) {
  27. result.add(precedessor.pop());
  28. } else if (Math.abs((double) precedessor.peek() - target) < Math.abs((double) successor.peek() - target)) {
  29. result.add(precedessor.pop());
  30. } else {
  31. result.add(successor.pop());
  32. }
  33. }
  34.  
  35. return result;
  36. }
  37.  
  38. private void getPredecessor(TreeNode root, double target, Stack<Integer> precedessor) {
  39. if (root == null) {
  40. return;
  41. }
  42.  
  43. getPredecessor(root.left, target, precedessor);
  44.  
  45. if (root.val > target) {
  46. return;
  47. }
  48.  
  49. precedessor.push(root.val);
  50.  
  51. getPredecessor(root.right, target, precedessor);
  52. }
  53.  
  54. private void getSuccessor(TreeNode root, double target, Stack<Integer> successor) {
  55. if (root == null) {
  56. return;
  57. }
  58.  
  59. getSuccessor(root.right, target, successor);
  60.  
  61. if (root.val <= target) {
  62. return;
  63. }
  64.  
  65. successor.push(root.val);
  66.  
  67. getSuccessor(root.left, target, successor);
  68. }
  69. }  

C++:

  1. class Solution {
  2. public:
  3. vector<int> closestKValues(TreeNode* root, double target, int k) {
  4. vector<int> res;
  5. priority_queue<pair<double, int>> q;
  6. inorder(root, target, k, q);
  7. while (!q.empty()) {
  8. res.push_back(q.top().second);
  9. q.pop();
  10. }
  11. return res;
  12. }
  13. void inorder(TreeNode *root, double target, int k, priority_queue<pair<double, int>> &q) {
  14. if (!root) return;
  15. inorder(root->left, target, k, q);
  16. q.push({abs(root->val - target), root->val});
  17. if (q.size() > k) q.pop();
  18. inorder(root->right, target, k, q);
  19. }
  20. };  

类似题目:

[LeetCode] 270. Closest Binary Search Tree Value 最近的二叉搜索树的值

  

All LeetCode Questions List 题目汇总

[LeetCode] 272. Closest Binary Search Tree Value II 最近的二叉搜索树的值 II的更多相关文章

  1. [LeetCode] 272. Closest Binary Search Tree Value II 最近的二分搜索树的值之二

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

  2. [LeetCode#272] Closest Binary Search Tree Value II

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

  3. [leetcode]272. Closest Binary Search Tree Value II二叉搜索树中最近的值2

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

  4. [LeetCode] Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树

    Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...

  5. [LeetCode] Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 这道 ...

  6. PAT A1099 Build A Binary Search Tree (30 分)——二叉搜索树,中序遍历,层序遍历

    A Binary Search Tree (BST) is recursively defined as a binary tree which has the following propertie ...

  7. Convert Sorted List to Binary Search Tree——将链表转换为平衡二叉搜索树 &&convert-sorted-array-to-binary-search-tree——将数列转换为bst

    Convert Sorted List to Binary Search Tree Given a singly linked list where elements are sorted in as ...

  8. 108 Convert Sorted Array to Binary Search Tree 将有序数组转换为二叉搜索树

    将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树.此题中,一个高度平衡二叉树是指一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1.示例:给定有序数组: [-10,-3,0,5,9], ...

  9. 41.Validate Binary Search Tree(判断是否为二叉搜索树)

    Level:   Medium 题目描述: Given a binary tree, determine if it is a valid binary search tree (BST). Assu ...

随机推荐

  1. windows pip使用国内源

    在这里我使用清华源来做示范 win+R 打开用户目录%HOMEPATH%,在此目录下创建 pip 文件夹,在 pip 目录下创建 pip.ini 文件, 内容如下, 在pip文件夹里新建的pip.in ...

  2. oracle数据库应用总结

    1------->>>>>>>>>>>>>>>>>>>>>>> ...

  3. CenterNet

    Objects as Points anchor-free系列的目标检测算法,只检测目标中心位置,无需采用NMS 1.主干网络 采用Hourglass Networks [1](还有resnet18 ...

  4. php正则表达式修饰符详解

    preg_match_all("/(.+)<\/form>/isU" , $string, $result); 这里/ 后面加了 3个修饰符 i 是 不区分大小写的匹配 ...

  5. 清楚webView的缓存

    +(void)clearCache{    NSHTTPCookie *cookie;    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage s ...

  6. 使用RegisterPointerInputTarget时的一些注意事项

    RegisterPointerInputTarget :允许调用者注册一个目标窗口,指定类型的所有指针输入都重定向到该窗口. 要使用它必须使 UIAccess = true,见下图 在设置完之后,需要 ...

  7. java作业利用递归解决问题

    第一题 利用递归求组合数 设计思想 (1)首先根据公式求,利用递归完成阶乘函数的初始化,并且通过调用阶乘,实现公式计算 (2)递推方法,根据杨辉三角的特点,设置二维数组,从上到下依次保存杨辉三角所得数 ...

  8. 《SaltStack技术入门与实践》—— Grains

    Grains 本章节参考<SaltStack技术入门与实践>,感谢该书作者: 刘继伟.沈灿.赵舜东 前几章我们已经了解SaltStack各个组件以及通过一个案例去熟悉它的各种应用,从这章开 ...

  9. 4.瀑布流js

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. k8s实战--redis主从--guestbook

    快速入门 实验:通过服务自动发现的redis主从 难点: 1,服务的自动发现,即如何确定coreDNS 已生效 2,redis的主从验证 遇到的问题: 1,Can't handle RDB forma ...