zoukankan      html  css  js  c++  java
  • [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 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

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 
    11 /*
    12 Time Complexity: O(n)
    13 Space Complexity:O(k)
    14 */
    15 class Solution {
    16     // choose a data structure which can do operations on both sides
    17     LinkedList<Integer> result = new LinkedList<>();
    18     
    19     public List<Integer> closestKValues(TreeNode root, double target, int k) {
    20         // corner case
    21         if (root == null) {return null;}
    22         // inorder traversal
    23         closestKValues(root.left, target, k);
    24     
    25         if (result.size() < k) {
    26             result.add(root.val);
    27             // maintain a K size sliding window such that items are closest to the target
    28         } else if(result.size() == k) {
    29             if (Math.abs(result.getFirst() - target) > (Math.abs(root.val - target))) {
    30                 result.removeFirst();
    31                 result.addLast(root.val);
    32             } 
    33         }
    34         // inorder traversal
    35         closestKValues(root.right, target, k);
    36         return result;
    37     }    
    38 }
  • 相关阅读:
    算法之冒泡排序(Java语言)
    算法之水仙花数(Java语言)
    md5加密解析
    Java项目中环境变量的问题
    外行码农进阶学习指导思想
    初识TCP
    const修饰符总结
    网格计算的三种体系结构概述
    虚函数的实现
    网络计算概述
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10767955.html
Copyright © 2011-2022 走看看