Leetcode-closest Binary Search Tree Value II

Source: Internet
Author: User

Given a non-empty binary search tree and a target value, find K values in the BST that is closest to the target.

Note:

    • Given target value is a floating point.
    • Assume k is always valid, which is: k ≤total nodes.
    • You is guaranteed to a unique set of K values in the BST is closest to the target.

Follow up:
Assume that the BST are balanced, could you solve it in less than O(n) runtime (where n = Total nodes)?

Analysis:

Use inorder Traverse, put all predecessors to a stack, for every successor, put all Pres that have 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 rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicList<integer> closestkvalues (TreeNode root,DoubleTargetintk) {Stack<Integer> pres =NewStack<integer>(); LinkedList<Integer> reslist =NewLinkedlist<integer>();        Closestkvaluesrecur (root,target,k,pres,reslist); //If Not enough in reslist, put to pres into reslist. This is because successor is too little.         while(Reslist.size () <k &&!Pres.empty ())        {Reslist.addfirst (Pres.pop ()); }        returnreslist; }     Public voidClosestkvaluesrecur (TreeNode Curnode,DoubleTargetintK, 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); }}

Leetcode-closest Binary Search Tree Value II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.