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

    Analysis:

    Use inorder traverse, put all predecessors into a stack, for every successor, put all pres that has smaller gap than that successor into resList and then put this successor into resList.

    Solution:

    /**
     * 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) {
            Stack<Integer> pres = new Stack<Integer>();
            LinkedList<Integer> resList = new LinkedList<Integer>();
            closestKValuesRecur(root,target,k,pres,resList);
            // If not enough in resList, put more pres into resList. This is because successor is too little.
            while (resList.size()<k && !pres.empty()){
                    resList.addFirst(pres.pop());
            }
            return resList;        
        }
    
        public void closestKValuesRecur(TreeNode curNode, double target, int k, Stack<Integer> pres, LinkedList<Integer> resList){
            if (curNode == null) return;
            if (resList.size()==k) return;
    
            // inorder traverse.
            closestKValuesRecur(curNode.left,target,k,pres,resList);
    
            // check curNode
            if (curNode.val >= target){
                while (resList.size()<k && !pres.empty() && target-pres.peek() < curNode.val-target){
                    resList.addFirst(pres.pop());
                }
                if (resList.size()<k){
                    resList.addLast(curNode.val);
                } else {
                    return;
                }
            } else {
                pres.push(curNode.val);
            }
    
            closestKValuesRecur(curNode.right,target,k,pres,resList);
        }
    }
  • 相关阅读:
    Pyinstaller(python打包为exe文件)
    matplotlib 填充颜色
    Visual Studio 2015 Enterprise
    latex中pdflatex与xelatex的区别
    latex插图续
    dva+umi+antd项目从搭建到使用(没有剖验证,不知道在说i什么)
    umi+dva+antd新建项目(亲测可用)
    HTTP缓存机制
    企业网站常见需求整理
    立足于运维与监控的前端框架 NoahV
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5836167.html
Copyright © 2011-2022 走看看