-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathclosest-val-bst.cpp
68 lines (52 loc) · 1.36 KB
/
closest-val-bst.cpp
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
63
64
65
66
class BST {
public:
int value;
BST *left;
BST *right;
BST(int val);
BST &insert(int val);
};
int findClosestValueInBst(BST *tree, int target);
int findClosestValueInBstHelper(BST *tree, int target, double closest)
// Average: O(log(n)) time | O(log(n)) space
// Worst: O(n) time | O(n) space
int findClosestValueInBst(BST *tree, int target) {
return findClosestValueInBstHelper(tree, target, DBL_MAX);
}
int findClosestValueInBstHelper(BST *tree, int target, double closest) {
if(tree == NULL) return closest;
if (abs(target - closest) > abs(target - tree->value)) {
closest = tree->value;
}
if (target < tree->value && tree->left != NULL) {
return findClosestValueInBstHelper(tree->left, target, closest);
}
else if (target > tree->value && tree->right != NULL) {
return findClosestValueInBstHelper(tree->right, target, closest);
}
else {
return closest;
}
}
// Iterative Solution
int findClosestValueInBst(BST *tree, int target) {
return findClosestValueInBstHelper(tree, target, DBL_MAX)
}
int findClosestValueInBstHelper(BST *tree, int target, double closest) {
BST *curr = tree;
while(curr!= NULL) {
if(abs(target - closest) > abs(target - curr->value)) {
closest = tree->value;
}
if(target > cur->value) {
cur = cur->right;
}
else if(target < cur->value) {
cur = cur->left;
}
else {
break;
}
}
return closest;
}