题目:

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. 制作C/C++动态链接库(dll)若干注意事项

    一.C\C++ 运行时库编译选项简单说明 问题:我的dll别人没法用 运行时库是个很复杂的东西,作为开发过程中dll制作需要了解的一部分,这里主要简单介绍一下如何选择编译选项. 在我们的开发过程中时常 ...

  2. REST API 基于ACCESS TOKEN 的权限解决方案

    REST 设计原则是statelessness的,而且但客户端是APP时,从APP发起的请求,不是基于bowers,无法带相同的sessionid,所以比较好的方案是每次请求都带一个accesstok ...

  3. JS 学习笔记--12---面向对象

    练习中使用的浏览器为IE10,如果各位朋友有不同意见或者本文有什么错误地方,望指正 ECMASCript有两种开发模式:函数式(面向过程)和面向对象.面向对象有一个很明显的标志,那就是类,我们可以通过 ...

  4. BZOJ2879 [Noi2012]美食节

    AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=2879 这题codevs上也有,不过数据不同:http://codevs.cn/proble ...

  5. BZOJ 2820 YY的GCD

    AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=2820 有种方法是枚举质数然后用BZOJ2301来做但是超时了... 具体式子大概张这样: ...

  6. Noip模拟考第三题——饥饿游戏

    饥饿游戏 (hungry.pas/c/cpp) [问题描述] Chanxer饿了,但是囊中羞涩,于是他去参加号称免费吃到饱的“饥饿游戏”. 这个游戏的规则是这样的,举办者会摆出一排 个食物,希望你能够 ...

  7. IIS8托管WCF服务

    WCF服务程序本身不能运行,需要通过其他的宿主程序进行托管才能调用WCF服务功能,常见的宿主程序有IIS,WAS,Windows服务,当然在学习WCF技术的时候一般使用控制台应用程序或WinForm程 ...

  8. ActionScript基本语法讲解

    var a:int = 3;var b:int = 4; b = 9; trace ("a的值为:"+a);trace ("b的值为:"+b); var x1: ...

  9. linux下解压命令大全(转载)

    .tar 解包:tar xvf FileName.tar 打包:tar cvf FileName.tar DirName (注:tar是打包,不是压缩!) ——————————————— .gz 解压 ...

  10. Topcoder SRM 630div 2

    A:不断的消除两个相邻的相等字符,简单题. 真心不习惯STL.. #include<iostream> #include <string> #include <vecto ...