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);
    }
}

 

转载于:https://www.cnblogs.com/lishiblog/p/5836167.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值