LeetCode Closest Binary Search Tree Value II
原题链接在这里:https://leetcode.com/problems/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 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)?
题解:
Inorder traversal. When que size == k, if que.peekFirst() is further from target, poll first. Otherwise, that means que.peekFirst() is closer, then there is no need to add current root val and there is no need to iterate root.right side, because it is even larger, and even further from target.
Time Complexity: O(n). Space: O(k). 若果不考虑recursion stack.
AC Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> closestKValues(TreeNode root, double target, int k) {
LinkedList<Integer> res = new LinkedList<>();
if(root == null || k <= 0){
return res;
} inorder(root, target, k, res);
return res;
} private void inorder(TreeNode root, double target, int k, LinkedList<Integer> que){
if(root == null){
return;
} inorder(root.left, target, k, que);
if(que.size() == k){
if(Math.abs(que.peek() - target) > Math.abs(root.val - target)){
que.pollFirst();
}else{
return;
}
} que.add(root.val);
inorder(root.right, target, k, que);
}
}
找出一个最小值,从BST中删掉这个key.
Time Complexity: O(k*logn).
/**
* 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> res = new ArrayList<Integer>();
if(root == null){
return res;
} for(int i = 0; i<k ;i++){
int closest = closestValue(root, target);
res.add(closest);
root = deleteNode(root, closest);
} return res;
} private int closestValue(TreeNode root, double target){
if(root == null){
return Integer.MAX_VALUE;
}
int closest = root.val;
double minDiff = Double.MAX_VALUE;
while(root != null){
if(Math.abs(root.val - target) < minDiff){
minDiff = Math.abs(root.val - target);
closest = root.val;
} if(target > root.val){
root = root.right;
}else if(target < root.val){
root = root.left;
}else{
return root.val;
}
}
return closest;
} private TreeNode deleteNode(TreeNode root, int key){
if(root == null){
return root;
} if(root.val > key){
root.left = deleteNode(root.left, key);
}else if(root.val < key){
root.right = deleteNode(root.right, key);
}else{
if(root.left == null){
return root.right;
}else if(root.right == null){
return root.left;
} int suc = findSuc(root.right);
root.val = suc;
deleteNode(root.right, suc);
}
return root;
} private int findSuc(TreeNode root){
int suc = root.val;
while(root.left != null){
root = root.left;
suc = root.val;
}
return suc;
}
}
类似Closest Binary Search Tree Value.
LeetCode Closest Binary Search Tree Value II的更多相关文章
- [LeetCode] 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] Closest Binary Search Tree Value 最近的二分搜索树的值
Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...
- LeetCode Closest Binary Search Tree Value
原题链接在这里:https://leetcode.com/problems/closest-binary-search-tree-value/ Given a non-empty binary sea ...
- [Locked] Closest Binary Search Tree Value & Closest Binary Search Tree Value II
Closest Binary Search Tree Value Given a non-empty binary search tree and a target value, find the ...
- [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 t ...
- [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 ...
- 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 close ...
- [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 ...
随机推荐
- 创建 maven 本地仓库; (五)
在 pom.xml 添加依赖包的时候,有时候会提示无法从 http://repo1.maven.org/maven2/ 获取的情况,这时可配置个本地仓库: 从网上下载 maven 仓库网站源码包 Ne ...
- mysql insert插入新形式,再也不需要拼接多重insert啦
注意一下,不能省略表中的任何字段.包括自增id.而且字段的顺序必须和插入表一致 原理是“表插表” INSERT INTO prod_attr select A.* from ( SELECT AS p ...
- Leetcode | Parentheses 相关
Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of ...
- hadoop MapReduce 笔记
1. MapReduce程序开发步骤 编写map 和 reduce 程序–> 单元测试 -> 编写驱动程序进行验证-> 本地数据集调试 -> 部署到集群运行 用 ...
- Web 在线文件管理器学习笔记与总结(5)修改文件内容
① 读出要修改的文件的内容 ② 进行修改 ③ 将修改后的内容写进文件 index.php: <?php require 'dir.func.php'; require 'file.func.ph ...
- redis缓存怎么存储对象
2.把对象Object存储到redis中,怎么存?memcache存取对象是序列化和反序列化 使用通用的序列化.反序列化(频繁的会很消耗cpu,使用Google Protocol Buffer,将对象 ...
- js 获取checkbox选中项目
# //获取选中项 $('#submit').click(function () { var check_list = [] $("input[name='ck']:checked" ...
- material design——设计文档
http://www.uisdc.com/comprehensive-material-design-note
- javaWeb中struts开发——helloworld
1.新建一个web项目 2.选中project,右键,选择MyElcipse,选择add struts capab...添加struts支持,然后自己命名包 3.Struts在建立jsp时,标签要到 ...
- laravel 部分路由取消csrf
// app/Http/Middleware/VerifyCsrfToken protected $except = [ 'webhook/*' ];