项目作者: eMahtab

项目描述 :
Closest Binary Search Tree Value
高级语言:
项目地址: git://github.com/eMahtab/closest-binary-search-tree-value.git


Closest Binary Search Tree Value

https://leetcode.com/problems/closest-binary-search-tree-value

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

Note:

  1. Given target value is a floating point.
  2. You are guaranteed to have only one unique value in the BST that is closest to the target.
    ```
    Example:

Input: root = [4,2,5,1,3], target = 3.714286

  1. 4

/ \
2 5
/ \
1 3

Output: 4

But if target is 3.5 and we are asked to return the smallest number which is closest to target,
then answer will be 3 and not 4 (both 3 and 4 have the same difference from target but 3 is smaller than 4) .

  1. # Implementation 1 : O(nlogn), inorder traversal, sort
  2. ```java
  3. class Solution {
  4. public int closestValue(TreeNode root, double target) {
  5. List<Integer> nums = new ArrayList();
  6. inorder(root, nums);
  7. Collections.sort(nums, (n1,n2) ->
  8. Double.compare(Math.abs(n1 - target), Math.abs(n2 - target)));
  9. return nums.get(0);
  10. }
  11. public void inorder(TreeNode node, List<Integer> nums) {
  12. if (node == null) return;
  13. inorder(node.left, nums);
  14. nums.add(node.val);
  15. inorder(node.right, nums);
  16. }
  17. }

Implementation 2 : O(h)

  1. class Solution {
  2. public int closestValue(TreeNode root, double target) {
  3. int closestValue = root.val;
  4. TreeNode node = root;
  5. while(node != null){
  6. if(Math.abs(node.val - target) < Math.abs(closestValue - target))
  7. closestValue = node.val;
  8. node = target < node.val ? node.left : node.right;
  9. }
  10. return closestValue;
  11. }
  12. }

Implementation 3 : O(h), If there are multiple answers, return the smallest number

  1. class Solution {
  2. public int closestValue(TreeNode root, double target) {
  3. int closestValue = root.val;
  4. TreeNode node = root;
  5. while(node != null){
  6. if(Math.abs(node.val - target) < Math.abs(closestValue - target) ||
  7. (Math.abs(node.val - target) == Math.abs(closestValue - target) && node.val < closestValue))
  8. closestValue = node.val;
  9. node = target < node.val ? node.left : node.right;
  10. }
  11. return closestValue;
  12. }
  13. }

References :

https://www.youtube.com/watch?v=_sz0Y4g1Gos

https://leetcode.com/problems/closest-binary-search-tree-value/editorial