[LeetCode] 272. Closest Binary Search Tree Value II 最近的二叉搜索树的值 II
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的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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. 这道 ...
- 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 ...
- 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 ...
- 108 Convert Sorted Array to Binary Search Tree 将有序数组转换为二叉搜索树
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树.此题中,一个高度平衡二叉树是指一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1.示例:给定有序数组: [-10,-3,0,5,9], ...
- 41.Validate Binary Search Tree(判断是否为二叉搜索树)
Level: Medium 题目描述: Given a binary tree, determine if it is a valid binary search tree (BST). Assu ...
随机推荐
- Codeforces 976 正方格蛇形走位 二维偏序包含区间 度数图构造 贪心心火牧最大dmg
A #include <bits/stdc++.h> using namespace std; typedef unsigned long long ull; int main() { i ...
- 5G技术被夸大?专家来测试一下
像大多数新技术一样,5G也带来了大量媒体宣传.这种炒作中有些伴随着事实的严重扭曲和5G技术实际功能的放大.但是,有一个普遍共识的说法是5G将实现“极速”,换句话说,与前几代产品相比,带宽要高得多. 这 ...
- Docker MongoDB 部署
docker search mongo 命令来查看可用版本: $ docker search mongo NAME DESCRIPTION STARS OFFICIAL AUTOMATED mongo ...
- Windows 7、Windows XP SP3关闭DEP堆栈执行保护
Windows XP SP3 在Windows XP SP3中,关闭DEP的方法是: 编辑C:\boot.ini,你大概会看到如下内容 [boot loader] timeout=30 default ...
- Hibernate方法save、update、merge、saveOrUpdate及get和load的区别
在看这几个方法区别之前,有必要了解hibernate实体对象的三种状态,点击查看 http://www.cnblogs.com/Y-S-X/p/8345754.html 一.update 和 merg ...
- aspose 模板输出
Dictionary<string, string> dictionnaryBig = new Dictionary<string, string>(); dictionnar ...
- jquery 3.1 tets
r.extend = r.fn.extend = function () { var a, b, c, d, e, f, g = arguments[0] || {}, h = 1, i = argu ...
- js 页面 保持状态 的方法
A -> B 带参数进去B页面, 刷新B页面还 保持状态 单机下一页, 改变请求参数, A->B 不带参数进去B页面 (不存在)当前状态保存在cookies中, 刷新页面,判断cooki ...
- Python3学习笔记(五):列表和元组
一.列表 列表是可变的--可以改变列表的内容 list函数可以把各种类型的序列拆分列表 >>> list('Hello') ['H', 'e', 'l', 'l', 'o'] 二.列 ...
- bash配置文件
bash的配置文件 一.shell的两种登录方式: 1.交互式登录: (1)直接通过终端输入账号密码登录 (2)使用"su - UserName" 切换的用户 执行顺序:/etc/ ...