1. 程式人生 > >[leetcode]270. Closest Binary Search Tree Value二叉搜尋樹中找target的最接近值

[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 }