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 }
  • 相关阅读:
    Angular Universal 学习笔记
    SAP Spartacus 如何获得当前渲染页面的 CMS 元数据
    Angular 服务器端渲染的学习笔记(二)
    Angular 服务器端渲染的学习笔记(一)
    第三方外部 Saas提供商如何跟使用 SAP 系统的客户进行对接接口集成
    如何从 SAP Spartacus Product Detail 页面,找到其 Angular 实现 Component 的位置
    具备自动刷新功能的 SAP ABAP ALV 报表
    C++学习目录
    c--条件编译
    c--文件读写--二进制
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10767955.html
Copyright © 2011-2022 走看看