标签:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<Integer> closestKValues(TreeNode root, double target, int k) { 12 List<Integer> result = new ArrayList<>(); 13 if (k == 0 || root == null) { 14 return result; 15 } 16 17 Stack<TreeNode> successor = new Stack<>(); 18 Stack<TreeNode> precessor = new Stack<>(); 19 20 initialStack(successor, root, true, target); 21 initialStack(precessor, root, false, target); 22 23 if(!successor.isEmpty() && !precessor.isEmpty() && successor.peek().val == precessor.peek().val) { 24 getNext(precessor, false); 25 } 26 27 while (result.size() < k) { 28 if (successor.isEmpty()) { 29 result.add(getNext(precessor, false)); 30 } else if (precessor.isEmpty()) { 31 result.add(getNext(successor, true)); 32 } else { 33 boolean sclose = Math.abs((double) successor.peek().val - target) < Math.abs((double)precessor.peek().val - target); 34 if (sclose) { 35 result.add(getNext(successor, true)); 36 } else { 37 result.add(getNext(precessor, false)); 38 } 39 } 40 } 41 return result; 42 } 43 44 private void initialStack(Stack<TreeNode> stack, TreeNode root, boolean successor, double target) { 45 while (root != null) { 46 if (root.val == target) { 47 stack.push(root); 48 break; 49 } else if (root.val > target == successor) { 50 stack.push(root); 51 root = successor ? root.left : root.right; 52 } else { 53 root = successor ? root.right : root.left; 54 } 55 } 56 } 57 58 private int getNext(Stack<TreeNode> stack, boolean successor) { 59 TreeNode current = stack.pop(); 60 int result = current.val; 61 current = successor ? current.right : current.left; 62 while (current != null) { 63 stack.push(current); 64 current = successor ? current.left : current.right; 65 } 66 return result; 67 } 68 }
Cloest Binary Search Tree Value II
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/5723603.html