-
Notifications
You must be signed in to change notification settings - Fork 0
/
Closest Neighbour in BST.cpp
83 lines (77 loc) · 1.7 KB
/
Closest Neighbour in 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//Recursion - 1.0
// Recursion
// Time complexity - O(Height of the tree)
// Space complexity- O(Height of thre tree)
class Solution {
public:
int help(Node* root,int& x)
{
//base case
if(!root)
return 0;
//recursive calls
//and small calculation
if(root->key==x)
return x;
int a;
if(root->key<x)
a=help(root->right,x);
else
a=help(root->left,x);
if(max(root->key,a)<=x)
return max(root->key,a);
else
return min(root->key,a);
}
int findMaxForN(Node* root, int n) {
int ans=help(root,n);
return ans==0 ? -1:ans;
}
};
// Recursion - 1.1
// Recursion
// Time complexity - O(Height of the tree)
// Space complexity- O(Height of thre tree)
class Solution {
public:
void help(Node* root,int& x,int& ans)
{
//base case
if(!root)
return ;
//recursive calls
//and small calculation
if(root->key<=x)
{
ans=root->key;
help(root->right,x,ans);
}
else
help(root->left,x,ans);
}
int findMaxForN(Node* root, int n) {
int ans=0;
help(root,n,ans);
return ans==0 ? -1:ans;
}
};
// Iterative
// Time complexity - O(Height of the tree)
// Space complexity- O(1)
class Solution {
public:
int findMaxForN(Node* root, int n) {
int ans=0;
while(root)
{
if(root->key<=n)
{
ans=root->key;
root=root->right;
}
else
root=root->left;
}
return ans==0 ? -1:ans;
}
};