forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClosestBinarySearchTreeValue.java
62 lines (55 loc) · 1.62 KB
/
ClosestBinarySearchTreeValue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package tree;
/**
* Created by gouthamvidyapradhan on 10/05/2017.
* 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.
Solution: Simple dfs recursive algorithm to find the closest match.
Worst case time complexity is O(h) where h is height of the tree
*/
public class ClosestBinarySearchTreeValue
{
/**
* TreeNode
*/
public static class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
private double absDiff = Double.MAX_VALUE;
private int closest;
/**
* Main method
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
TreeNode root = new TreeNode(10);
root.left = new TreeNode(9);
root.left.left = new TreeNode(8);
System.out.println(new ClosestBinarySearchTreeValue().closestValue(root, 7.63354D));
}
/**
* Find closest
* @param root Root node
* @param target double target
* @return closest value
*/
public int closestValue(TreeNode root, double target)
{
if(root == null) return closest;
if(Math.abs(target - root.val) < absDiff)
{
absDiff = Math.abs(target - root.val);
closest = root.val;
}
if(root.val > target)
return closestValue(root.left, target);
else return closestValue(root.right, target);
}
}