标签:
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)?
Hint:
getPredecessor(N)
, which returns the next smaller node to N.getSuccessor(N)
, which returns the next larger node to N.
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> res = new ArrayList<Integer>(); 13 LinkedList<Integer> stack = new LinkedList<Integer>(); 14 LinkedList<Integer> queue = new LinkedList<Integer>(); 15 inorder(root, target, stack, queue); 16 for (int i=0; i<k; i++) { 17 if (stack.isEmpty()) res.add(queue.poll()); 18 else if (queue.isEmpty()) res.add(stack.pop()); 19 else { 20 int s = stack.peek(); 21 int q = queue.peek(); 22 if (Math.abs(s-target) < Math.abs(q-target)) { 23 res.add(s); 24 stack.pop(); 25 } 26 else { 27 res.add(q); 28 queue.poll(); 29 } 30 } 31 } 32 return res; 33 } 34 35 public void inorder(TreeNode root, double target, LinkedList<Integer> stack, LinkedList<Integer> queue) { 36 if (root == null) return; 37 inorder(root.left, target, stack, queue); 38 if (root.val < target) { 39 stack.push(root.val); 40 } 41 else { 42 queue.offer(root.val); 43 } 44 inorder(root.right, target, stack, queue); 45 } 46 }
Leetcode: Closest Binary Search Tree Value II
标签:
原文地址:http://www.cnblogs.com/EdwardLiu/p/5072723.html