[leetcode]270. Closest Binary Search Tree Value二叉搜索树中找target的最接近值


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

Note:

  • Given target value is a floating point.
  • 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

    4
   / \
  2   5
 / \
1   3

Output: 4

题目

给定一棵二叉搜索树和一个target,求出其节点中最接近该target的值。

思路

1. based on the BST's attribution ( left < root < right), we use binary search

代码

 1 class Solution {
 2     public int closestValue(TreeNode root, double target) {
 3         int result = root.val;   
 4         while(root != null){
 5             //update result if the current value is closer to target
 6             if(Math.abs(target - root.val) < Math.abs(target - result)){
 7                 result = root.val;
 8             }      
 9             //binary search
10             root = root.val > target? root.left: root.right;
11         }     
12         return result;
13     }
14 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9823968.html