-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathCloestInBST.java
More file actions
53 lines (45 loc) · 1.08 KB
/
CloestInBST.java
File metadata and controls
53 lines (45 loc) · 1.08 KB
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
package algorithm.recursive;
/**
* Find the closest element in a BST.
*
*/
public class CloestInBST {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public int closest(TreeNode root, int target) {
int[] res = {-1};
int[] diff = {Integer.MAX_VALUE};
closest(root, target, res, diff);
return res[0];
}
private void closest(TreeNode node, int target, int[] curRes, int[] diff) {
if (node == null) {
return;
}
int curDiff = Math.abs(node.val - target);
if (node.val == target) {
curRes[0] = node.val;
diff[0] = 0;
}
else if (node.val < target) { // search the right sub-tree
if (curDiff < diff[0]) {
curRes[0] = node.val;
diff[0] = curDiff;
}
closest(node.right, target, curRes, diff);
}
else { // search the left sub-tree
if (curDiff < diff[0]) {
curRes[0] = node.val;
diff[0] = curDiff;
}
closest(node.left, target, curRes, diff);
}
}
}