首页 > 其他 > 详细

LeetCode-Closest Binary Search Tree Value

时间:2016-07-13 20:20:28      阅读:238      评论: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.

Analysis:

  Find the two values before and after the target. Use two integer to record the most recent two values.

 

Solution:

  

 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 class Pair {
12         int val1;
13         int val2;
14 
15         Pair(int v1, int v2) {
16             val1 = v1;
17             val2 = v2;
18         }
19     }
20 
21     public boolean closestValueRecur(TreeNode curNode, double target, Pair res) {
22         if (curNode == null)
23             return false;
24 
25         if (closestValueRecur(curNode.left, target, res))
26             return true;
27         res.val1 = res.val2;
28         res.val2 = curNode.val;
29         if (res.val1 <= target && res.val2 >= target)
30             return true;
31         if (closestValueRecur(curNode.right, target, res))
32             return true;
33 
34         return false;
35     }
36 
37     public int closestValue(TreeNode root, double target) {
38         Pair res = new Pair(Integer.MIN_VALUE, Integer.MIN_VALUE);
39 
40         closestValueRecur(root, target, res);
41 
42         if (res.val1 == Integer.MIN_VALUE)
43             return res.val2;
44         if (res.val2 <= target)
45             return res.val2;
46 
47         if (target - res.val1 < res.val2 - target)
48             return res.val1;
49         else
50             return res.val2;
51     }
52 }

 

LeetCode-Closest Binary Search Tree Value

原文:http://www.cnblogs.com/lishiblog/p/5667153.html

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