Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?
O(N)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * }*/classSolution{publicList<Integer>closestKValues(TreeNoderoot,doubletarget,intk){List<Integer> res =newArrayList<>();if(root ==null)return res;Stack<TreeNode> stack =newStack<>();TreeNode cur = root;while(!stack.isEmpty()|| cur !=null){while(cur !=null){stack.push(cur); cur =cur.left;} cur =stack.pop();if(res.size()< k){res.add(cur.val);}else{if(Math.abs(cur.val- target)<Math.abs(res.get(0)- target)){res.add(cur.val);res.remove(0);}} cur =cur.right;}return res;}}
use two stack to save the treenode, one stack is for treenode val smaller than target, other one is for treenode val larger or equal with target, . then if the res.size < k, just get peek of the two stack, to compare the distance, after select one, update the stack. for example, I picked the stack from the smaller value stack, then I go to the stack.pop node's right, which is larger than the picked node. Then go to the node's left, this is trying to find the fist node larger than the peek(). same with larger stack.