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:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> closestKValues(TreeNode root, double target, int k) {
LinkedList<Integer> res = new LinkedList<>();
inOrderTraversal(root, target, k, res);
return res;
} private void inOrderTraversal(TreeNode root, double target, int k, LinkedList<Integer> res) {
if (root == null) {
return;
}
inOrderTraversal(root.left, target, k, res);
if (res.size() < k) {
res.add(root.val);
} else if(res.size() == k) {
if (Math.abs(res.getFirst() - target) > (Math.abs(root.val - target))) {
res.removeFirst();
res.addLast(root.val);
} else {
return;
}
}
inOrderTraversal(root.right, target, k, res);
}
}

Java:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private PriorityQueue<Integer> minPQ;
private int count = 0;
public List<Integer> closestKValues(TreeNode root, double target, int k) {
minPQ = new PriorityQueue<Integer>(k);
List<Integer> result = new ArrayList<Integer>(); inorderTraverse(root, target, k); // Dump the pq into result list
for (Integer elem : minPQ) {
result.add(elem);
} return result;
} private void inorderTraverse(TreeNode root, double target, int k) {
if (root == null) {
return;
} inorderTraverse(root.left, target, k); if (count < k) {
minPQ.offer(root.val);
} else {
if (Math.abs((double) root.val - target) < Math.abs((double) minPQ.peek() - target)) {
minPQ.poll();
minPQ.offer(root.val);
}
}
count++; inorderTraverse(root.right, target, k);
}
} 

Java:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution { public List<Integer> closestKValues(TreeNode root, double target, int k) {
PriorityQueue<Double> maxHeap = new PriorityQueue<Double>(k, new Comparator<Double>() {
@Override
public int compare(Double x, Double y) {
return (int)(y-x);
}
});
Set<Integer> set = new HashSet<Integer>(); rec(root, target, k, maxHeap, set); return new ArrayList<Integer>(set);
} private void rec(TreeNode root, double target, int k, PriorityQueue<Double> maxHeap, Set<Integer> set) {
if(root==null) return;
double diff = Math.abs(root.val-target);
if(maxHeap.size()<k) {
maxHeap.offer(diff);
set.add(root.val);
} else if( diff < maxHeap.peek() ) {
double x = maxHeap.poll();
if(! set.remove((int)(target+x))) set.remove((int)(target-x));
maxHeap.offer(diff);
set.add(root.val);
} else {
if(root.val > target) rec(root.left, target, k, maxHeap,set);
else rec(root.right, target, k, maxHeap, set);
return;
}
rec(root.left, target, k, maxHeap, set);
rec(root.right, target, k, maxHeap, set);
}
}

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

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> closestKValues(TreeNode root, double target, int k) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
} Stack<Integer> precedessor = new Stack<>();
Stack<Integer> successor = new Stack<>(); getPredecessor(root, target, precedessor);
getSuccessor(root, target, successor); for (int i = 0; i < k; i++) {
if (precedessor.isEmpty()) {
result.add(successor.pop());
} else if (successor.isEmpty()) {
result.add(precedessor.pop());
} else if (Math.abs((double) precedessor.peek() - target) < Math.abs((double) successor.peek() - target)) {
result.add(precedessor.pop());
} else {
result.add(successor.pop());
}
} return result;
} private void getPredecessor(TreeNode root, double target, Stack<Integer> precedessor) {
if (root == null) {
return;
} getPredecessor(root.left, target, precedessor); if (root.val > target) {
return;
} precedessor.push(root.val); getPredecessor(root.right, target, precedessor);
} private void getSuccessor(TreeNode root, double target, Stack<Integer> successor) {
if (root == null) {
return;
} getSuccessor(root.right, target, successor); if (root.val <= target) {
return;
} successor.push(root.val); getSuccessor(root.left, target, successor);
}
}  

C++:

class Solution {
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
vector<int> res;
priority_queue<pair<double, int>> q;
inorder(root, target, k, q);
while (!q.empty()) {
res.push_back(q.top().second);
q.pop();
}
return res;
}
void inorder(TreeNode *root, double target, int k, priority_queue<pair<double, int>> &q) {
if (!root) return;
inorder(root->left, target, k, q);
q.push({abs(root->val - target), root->val});
if (q.size() > k) q.pop();
inorder(root->right, target, k, q);
}
};  

类似题目:

[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. host.conf - 解析配置文件

    DESCRIPTION (描述) 文件 /etc/host.conf 包含了为解析库声明的配置信息. 它应该每行含一个配置关键字, 其后跟着合适的配置信息. 系统识别的关键字有: order, tri ...

  2. js node 节点 原生遍历 createNodeIterator

    1.createIterator msn: https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator v ...

  3. docker常用技巧

    1:运行中容器如何保存为一个镜像? docker commit 容器名字 镜像名字 2:怎么给容器增加名字 docker rename 容器id(或名字)name(新名字) 3:docker中的Doc ...

  4. AIX 6.1创建逻辑卷并挂载【smitty】

    1.创建卷组 #mkvg  -y   datavg     hdisk2   hdisk3   #smitty   vg

  5. associate.py 源代码 及 使用方法

    ORB_SLAM2运行RGBD数据集需要使用图片序列信息 使用以下代码进行汇集: #!/usr/bin/python # Software License Agreement (BSD License ...

  6. mapper映射文件配置之select、resultMap(转载)

    原文地址:http://www.cnblogs.com/dongying/p/4073259.html 先看select的配置吧: <select         <!-- 1. id ( ...

  7. SpringMVC @PathVariable注解

    下面用代码来演示@PathVariable传参方式 @RequestMapping("/user/{id}") public String test(@PathVariable(& ...

  8. 使用注解方式实现账户的CRUD

    1 需求和技术要求 1.1 需求 实现账户的CRUD. 1.2 技术要求 使用Spring的IOC实现对象的管理. 使用QueryRunner作为持久层的解决方案. 使用C3p0作为数据源. 2 环境 ...

  9. 【NOIP2016提高A组集训第13场11.11】最大匹配

    题目 mhy12345学习了二分图匹配,二分图是一种特殊的图,其中的点可以分到两个集合中,使得相同的集合中的点两两没有连边. 图的"匹配"是指这个图的一个边集,里面的边两两不存在公 ...

  10. 【NOIP2016提高A组五校联考2】running

    题目 小胡同学是个热爱运动的好孩子. 每天晚上,小胡都会去操场上跑步,学校的操场可以看成一个由n个格子排成的一个环形,格子按照顺时针顺序从0 到n- 1 标号. 小胡观察到有m 个同学在跑步,最开始每 ...