LeetCode-Closest Binary Search Tree Value

LiBlog發表於2016-07-13

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 }

 

相關文章