题目:

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. nodejs tools

    1.supervisor npm install supervisor -g supervisor app.js cd public cd bin supervisor www http://www. ...

  2. C++中栈的出栈,入栈规则:A,B,C,D,E

    考题: 栈底至栈顶一次存放元素 ABCD 在第五个元素E入栈之前  栈中元素可以出栈,则出栈序列可能是_____a d___________. a.  ABCED b.  DBCEA   c.  CD ...

  3. 关于js with语句的一些理解

    关于js with语句的一些理解   今天看到js的with语句部分,书中写到,with语句接收的对象会添加到作用域链的前端并在代码执行完之后移除.看到这里,我有两点疑问,添加到作用域链前端是不是指对 ...

  4. 14、到底改如何区分android的平板、电视、手机

    在没有出现android电视之前,如果要区分平板和手机有很多种方法: 方法1:看是否有通话功能 public boolean isTabletDevice() { TelephonyManager t ...

  5. SL410K 在Ubuntu禁用触摸板

    由于之前把系统自带的恢复去了,然后TouchPad一直不能禁用,而后我的410k就只装上ubuntu,想不到在ubuntu上,禁用/启用 触摸板这么方便. http://askubuntu.com/q ...

  6. 从Theano到Lasagne:基于Python的深度学习的框架和库

    从Theano到Lasagne:基于Python的深度学习的框架和库 摘要:最近,深度神经网络以“Deep Dreams”形式在网站中如雨后春笋般出现,或是像谷歌研究原创论文中描述的那样:Incept ...

  7. VS开发工具 不会在异常的地方停止的问题.

    启用"仅我的代码"

  8. 关于mysql 连接数

    mysql基本维护,就必须要知道连接数 进入mysql ,show status    Threads_connected  当前的连接数    Connections  试图连接到(不管是否成功)M ...

  9. NSOJ 鬼泣

    今天组队赛的一道最短路的题,给你一个矩阵,矩阵上有L,R,G,A,分别表示当你到达这个点的时候你要向左,向右,向前,向后走,如果要向别的方向走需要花费1点的魔力,正常情况下走需要花费1点的时间.问花费 ...

  10. poj 3686

    The Windy's Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 3791   Accepted: 1631 Descr ...