-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
closest_bst_value.cpp
76 lines (66 loc) · 2.02 KB
/
closest_bst_value.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
67
68
69
70
71
72
73
74
75
76
/*
* Given a non-empty binary search tree and a target value,
* find the value in the BST that is closest to the target.
* Also, to note that the target value is a floating point.
* There will be only one unique value which is closest to the target.
*/
#include <iostream>
#include <limits>
#include <cmath>
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int d):
data{d}, left{nullptr}, right{nullptr}{}
};
int closest_bst_value(TreeNode* root, double target)
{
// Tree is non-empty, so root is always valid.
int curr_value = root->data;
TreeNode* child = (target < curr_value) ? (root->left) : (root->right);
if (!child) {
return curr_value;
}
int child_value = closest_bst_value(child, target);
return std::abs(curr_value - target) <
std::abs(child_value- target) ? curr_value : child_value;
}
int closest_bst_value_iterative(TreeNode* root, double target)
{
int closest = root->data;
while (root != nullptr)
{
if (std::abs(target - closest) >= std::abs(target - root->data)) {
closest = root->data;
}
root = target < root->data ? root->left : root->right;
}
return closest;
}
void print_inorder(TreeNode* root)
{
if (root != nullptr) {
print_inorder(root->left);
std::cout << root->data << " ";
print_inorder(root->right);
}
}
int main()
{
TreeNode* root = new TreeNode(10);
root->left = new TreeNode(5);
root->right = new TreeNode(15);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(7);
root->right->left = new TreeNode(12);
root->right->right = new TreeNode(16);
std::cout << "Inorder traversal of tree: ";
print_inorder(root);
std::cout << std::endl;
std::cout << "Closest value from 3.6778 is :" << closest_bst_value(root, 3.6778)
<< std::endl;
std::cout << "(Iterative) Closest value from 3.6778 is :"
<< closest_bst_value_iterative(root, 3.6778) << std::endl;
return 0;
}