题目:

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:
      1. getPredecessor(N), which returns the next smaller node to N.
      2. 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.

链接:  http://leetcode.com/problems/closest-binary-search-tree-value-ii/

题解:

一开始思路非常不明确,看了不少discuss也不明白为什么。在午饭时间从头仔细想了一下,像Closest Binary Search Tree Value I一样,追求O(logn)的解法可能比较困难,但O(n)的解法应该不难实现。我们可以使用in-order的原理,从最左边的元素开始,维护一个Deque或者doubly linked list,将这个元素的值从后端加入到Deque中,然后继续遍历下一个元素。当Deque的大小为k时, 比较当前元素和队首元素与target的差来尝试更新deque。循环结束条件是队首元素与target的差更小或者遍历完全部元素。这样的话时间复杂度是O(n), 空间复杂度应该是O(k)。

Time Complexity - O(n), Space Complexity - 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) {
LinkedList<Integer> res = new LinkedList<>();
inOrder(root, target, k, res);
return res;
} private void inOrder(TreeNode root, double target, int k, LinkedList<Integer> res) {
if(root == null) {
return;
}
inOrder(root.left, target, k, res);
if(res.size() == k) {
if(Math.abs(res.get(0) - target) >= Math.abs(root.val - target)) {
res.removeFirst();
res.add(root.val);
} else {
return;
}
} else {
res.add(root.val);
}
inOrder(root.right, target, k, res);
}
}

二刷:

还是使用inorder traversal来遍历树,同时维护一个size为k的LinkedList或者Deque。这个原理类似于sliding window。

Java:

Time Complexity - O(n), Space Complexity - 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) {
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);
}
}

Reference:

https://leetcode.com/discuss/55261/efficient-python

https://leetcode.com/discuss/70577/java-in-order-traversal-1ms-solution

https://leetcode.com/discuss/64713/clear-java-solution-with-one-stack-one-linkedlist

https://leetcode.com/discuss/64713/clear-java-solution-with-one-stack-one-linkedlist

https://leetcode.com/discuss/69220/2-ms-o-n-and-6-ms-o-logn-java-solution

https://leetcode.com/discuss/55240/ac-clean-java-solution-using-two-stacks

https://leetcode.com/discuss/55682/o-logn-java-solution-with-two-stacks-following-hint

https://leetcode.com/discuss/55486/java-two-stacks-iterative-solution

https://leetcode.com/discuss/64713/clear-java-solution-with-one-stack-one-linkedlist

https://leetcode.com/discuss/71820/java-5ms-iterative-following-hint-o-klogn-time-and-space

https://leetcode.com/discuss/70577/java-in-order-traversal-1ms-solution

272. Closest Binary Search Tree Value 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 最近的二叉搜索树的值 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. [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 ...

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

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

  8. LeetCode Closest Binary Search Tree Value II

    原题链接在这里:https://leetcode.com/problems/closest-binary-search-tree-value-ii/ 题目: Given a non-empty bin ...

  9. [Swift]LeetCode272. 最近的二分搜索树的值 II $ 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. 程序调试手段之gdb, vxworks shell

    调试一个程序主要用到的功能: 启动程序 设置函数断点 设置数据断点 单步执行 查看内存值 修改内存值 linux下的gdb,和vxworks下的shell 虽然使用方式和调试命令略有不同,但是都能满足 ...

  2. token验证-微信公众平台开发3(asp.net)

    童鞋们直接看代码吧:(我这里是ashx处理程序写的类,开发过网站的一般都知道) <%@ WebHandler Language="C#" class="weixin ...

  3. 设计模式之工厂模式(Factory)

    设计模式的工厂模式一共有三种:简单工厂模式,工厂模式,抽象工厂模式 简单工厂模式原理:只有一个工厂类,通过传参的形式确定所创建的产品对象种类 代码如下: #include <stdio.h> ...

  4. 升级到win8.1后除IE11外,其它浏览器无法打开网页解决办法

    原文 : http://productforums.google.com/forum/#!topic/chrome/TUDjVQzf4Os 用管理员方式打开cmd 输入 netsh winsock r ...

  5. Task相关

    1.Task的优势: 1)把任务当成变量来用,可以作为参数而传递: 2)可以捕获到异步操作中发生的异常. 2.开始异步 Task.Factory.StartNew(() => Thread.Sl ...

  6. nsight 使用问题

    slot 0 offset 0 stride DXGI_FORMAT_r32b32g32_FLOAT 这样一个memory 100.0000, 100.0000,10.0000,1.0000 stri ...

  7. 使用微信JSSDK自定义分享内容

    微信在6.0.2.58版本以后开始使用新的api,在Android系统中不能用以前的代码来自定义分享内容了. 现在自定义内容的方法走的是公众号的一套流程 1获取access_token 2得到toke ...

  8. [百度空间] [原] 全局operator delete重载到DLL

    由于很久没有搞内存管理了,很多细节都忘记了今天项目要用到operator delete重载到DLL,发现了问题,网上搜索以后,再对比以前写的代码,发现了问题:原来MSVC默认的operator new ...

  9. asp.net 分布式缓存

    之前Velocity已被 集成到App Fabric(包含有WCF监控==)中.   网络Velocity使用大多是针对老版本:  老版本的下载地址:  http://www.microsoft.co ...

  10. Sqlite基础及其与SQLServer语法差异

    1 TOP 这是一个大家经常问到的问题,例如在SQLSERVER中可以使用如下语句来取得记录集中的前十条记录: SELECT TOP 10 * FROM [index] ORDER BY indexi ...