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.

Example:

Input: root = [4,2,5,1,3], target = 3.714286, and k = 2

    4
/ \
2 5
/ \
1 3 Output: [4,3]

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

题意

和之前一样,不过这次要找的是最接近的k个值。

Solution1:

1.  Based on BST's attributes, if we traversal BST inorder,  each node will be in acsending order

2. we choose a data structure which can help operate on both sides(LinkedList or Deque), maintaining a K size sliding window

once there is a new item,

we check diff (1) next item vs target

(2) leftMost item vs target

code

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ /*
Time Complexity: O(n)
Space Complexity:O(k)
*/
class Solution {
// choose a data structure which can do operations on both sides
LinkedList<Integer> result = new LinkedList<>(); public List<Integer> closestKValues(TreeNode root, double target, int k) {
// corner case
if (root == null) {return null;}
// inorder traversal
closestKValues(root.left, target, k); if (result.size() < k) {
result.add(root.val);
// maintain a K size sliding window such that items are closest to the target
} else if(result.size() == k) {
if (Math.abs(result.getFirst() - target) > (Math.abs(root.val - target))) {
result.removeFirst();
result.addLast(root.val);
}
}
// inorder traversal
closestKValues(root.right, target, k);
return result;
}
}

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

  1. [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 ...

  2. [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 ...

  3. [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 ...

  4. 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 ...

  5. LC 272. Closest Binary Search Tree Value II 【lock,hard】

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

  6. LeetCode OJ:Binary Search Tree Iterator(二叉搜索树迭代器)

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  7. [LeetCode] 98. Validate Binary Search Tree(是否是二叉搜索树) ☆☆☆

    描述 解析 二叉搜索树,其实就是节点n的左孩子所在的树,每个节点都小于节点n. 节点n的右孩子所在的树,每个节点都大于节点n. 定义子树的最大最小值 比如:左孩子要小于父节点:左孩子n的右孩子要大于n ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. jquery datatable测试部分代码(仅自用)

    创建一个四列的datatable表,第四列为表格里的按钮设置,respond为JSON对象数组. $('#example').DataTable({        //每页显示十条数据        ...

  2. projective dynamics的global solve中 引入拉格朗日乘子的简化方法

    想了一下使用乘子法还是可行的/做一个简化.在约束C(xn) 在C(xn-1)处线性展开 (n是时间步骤)具体推导留作备份等有时间了去代码实现 3式是一个典型的LCP问题 用PGS就行 左边的系数部分依 ...

  3. vs2015中SQLSERVER数据库项目引用系统视图

    近期使用VS中的SQLSERVER数据库项目进行项目开发,由于有很多自动化脚本会访问系统视图,例如sysobjects之类的,在项目中的脚本总是提示无法解析的引用,解决办法如下: 添加数据库引用 添加 ...

  4. 数据库新增“自动添加”类字段 auto_now_add 如何不影响之前数据

    django 中的模版为例:time = models.DateTimeField('创建时间', auto_now_add=True)这样显然是不行的.那么.我们可以考虑先给前面数据一个默认值迁移一 ...

  5. 自动生成构造方法、getter、setter

    前言 ​ 一直很想知道IDE是如何自动去生成类的构造和getter.setter方法,大概是有个想法,获取当前的类,利用反射去获取属性名和类型,然后生成,所以我想自己试试. 写个模板类 package ...

  6. python shutil模块&random模块

    shutil模块 import shutil shutil.copyfileobj(open("os_.py", "r"), open("os_2.p ...

  7. Linux部署笔记分享

    # Linux部署 ## 安装lrzsz1. 安装lrzsz: yum -y install lrzsz2. 进入tmp目录3. rz 上传安装文件 jdk-8u65-linux-x64.tar.gz ...

  8. [HTML]将错误alert出来[转]

    <script type="text/javascript"> /** * @param {String} errorMessage 错误信息 * @param {St ...

  9. drf框架之跨域问题的解决与缓存问题

    什么是跨域问题呢: 1. 跨域问题: CORS 跨域资源共享: 有简单请求 和非简单请求 简单请求: 只要符合如下两条,就是简单请求,否则则是非简单请求 (1) 请求方法是以下三种方法之一: HEAD ...

  10. Unable to locate appropriate constructor on class报错

    在项目开发中,使用Hibernate里的JPA criteria查询,但是在写完之后使用时,会报错:Unable to locate appropriate constructor on class, ...