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

    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.
      Show More Hint 
    Hide Company Tags
     Google
    Hide Tags
     Tree Stack
    Show Similar Problems
     用inorder来做 , bst inorder是有序的。
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
     //use inorder it will be a increase array
    public class Solution {
        public List<Integer> closestKValues(TreeNode root, double target, int k) {
            List<Integer> res = new LinkedList<Integer>();
            getClosestKValues(res, root, target, k);
            return res;
        }
        public void getClosestKValues(List<Integer> res, TreeNode root, double target, int k){
            if(root == null) return;
            getClosestKValues(res, root.left, target, k);
            if(res.size() == k){
                if(Math.abs(res.get(0) - target) > Math.abs(root.val - target)){
                    res.remove(0);
                    res.add(root.val);
                }
                else
                    return;
            }
            else
                res.add(root.val);
            getClosestKValues(res, root.right, target, k);
        }
    }
  • 相关阅读:
    c#冒泡排序算法和快速排序算法
    sqlserver 索引
    varchar和Nvarchar区别
    trigger
    sql语句
    超实用压力测试工具-ab工具
    js 页面离开前触发事件
    C# websocket与html js实现文件发送与接收处理
    C# socket编程 使用fleck轻松实现对话 https://github.com/statianzo/Fleck
    C# socket编程 使用udp实现单对单的连接对话
  • 原文地址:https://www.cnblogs.com/joannacode/p/5955051.html
Copyright © 2011-2022 走看看