首页 > 其他 > 详细

270. Closest Binary Search Tree Value

时间:2016-03-31 14:10:57      阅读:141      评论:0      收藏:0      [点我收藏+]

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.
 1 Solution 1. Iteration
 2 /**
 3  * Definition for a binary tree node.
 4  * public class TreeNode {
 5  *     int val;
 6  *     TreeNode left;
 7  *     TreeNode right;
 8  *     TreeNode(int x) { val = x; }
 9  * }
10  */
11 public class Solution {
12     public int closestValue(TreeNode root, double target) {
13         double diff = Double.MAX_VALUE;
14         int val = root.val;
15         
16         while (root != null) {
17             if (diff > Math.abs(root.val - target)) {
18                 val = root.val;
19                 diff = Math.abs(root.val - target);
20             }
21             if (root.val > target) {
22                 root = root.left;
23             } else {
24                 root = root.right;
25             }
26         } 
27         
28         return val;
29     }
30 }
31 
32 Solution 2. Recursion
33 public class Solution {
34     public int closestValue(TreeNode root, double target) {
35         int a = root.val;
36         TreeNode kid = target < a ? root.left : root.right;
37         if (kid == null) return a;
38         int b = closestValue(kid, target);
39         return Math.abs(a - target) < Math.abs(b - target) ? a : b;
40     }    
41 }

 

270. Closest Binary Search Tree Value

原文:http://www.cnblogs.com/joycelee/p/5340720.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!