[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 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)?

最接近的二叉搜索树的值版本二。版本一在此。题意是给一个二叉树,一个浮点数target和一个K,请返回二叉树中val最接近target的K个节点的值。

discussion里面的最高票答案是用两个stack做,一个存储target之前所有的前驱节点,一个存储所有的后驱节点,判断栈顶元素与target差值谁更接近而决定从哪个栈弹出元素加到结果集。我个人觉得这个解法的代码实现起来不是很轻松,我这里给出的是deque双端队列的解法。思路是用中序遍历先得到整棵树的节点,会是一个升序的数组;接着把这个数组放进一个双端队列,之后判断队首和队尾的元素谁跟target的差值更大,而决定将哪个元素弹出队列;终止条件是队列元素不能小于K。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public List<Integer> closestKValues(TreeNode root, double target, int k) {
 3         // Deque<Integer> dq = new ArrayDeque<>();
 4         Deque<Integer> dq = new LinkedList<>();
 5         inorder(root, dq);
 6         while (dq.size() > k) {
 7             if (Math.abs(dq.peekFirst() - target) > Math.abs(dq.peekLast() - target)) {
 8                 dq.pollFirst();
 9             } else {
10                 dq.pollLast();
11             }
12         }
13         return new ArrayList<Integer>(dq);
14     }
15 
16     public void inorder(TreeNode root, Deque<Integer> dq) {
17         if (root == null) {
18             return;
19         }
20         inorder(root.left, dq);
21         dq.add(root.val);
22         inorder(root.right, dq);
23     }
24 }

 

JavaScript实现

 1 /**
 2  * @param {TreeNode} root
 3  * @param {number} target
 4  * @param {number} k
 5  * @return {number[]}
 6  */
 7 var closestKValues = function (root, target, k) {
 8     var helper = function (root, dq) {
 9         if (root == null) {
10             return;
11         }
12         helper(root.left, dq);
13         dq.push(root.val);
14         helper(root.right, dq);
15     }
16     let dq = [];
17     helper(root, dq);
18     while (dq.length > k) {
19         if (Math.abs(dq[0] - target) > Math.abs(dq[dq.length - 1] - target)) {
20             dq.shift();
21         } else {
22             dq.pop();
23         }
24     }
25     return dq;
26 };

 

LeetCode 题目总结

posted @ 2020-03-21 14:32  CNoodle  阅读(353)  评论(0)    收藏  举报