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