-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClosestNeighborinBST.cpp
More file actions
108 lines (94 loc) · 2.01 KB
/
Copy pathClosestNeighborinBST.cpp
File metadata and controls
108 lines (94 loc) · 2.01 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node *left;
struct Node *right;
Node(int x){
key = x;
left = NULL;
right = NULL;
}
};
void insert(Node ** tree, int val)
{
Node *temp = NULL;
if(!(*tree))
{
temp = new Node(val);
*tree = temp;
return;
}
if(val < (*tree)->key)
{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->key)
{
insert(&(*tree)->right, val);
}
}
int mini=INT_MAX;
int findMaxForN(Node* root, int N,int size);
int main()
{
int T;
cin>>T;
while(T--)
{
Node* root=NULL;
int n, k;
cin>>n;
mini=INT_MAX;
for(int i=0;i<n;i++)
{
cin>>k;
insert(&root, k);
}
int s;
cin>>s;
cout<<findMaxForN(root,s,n)<<endl;
}
return 0;
}// } Driver Code Ends
/*int findMaxForN(Node* root, int N,int size)
{
//greatest number is find in the right subtree at the last
node* greatest=root[N-1];
//traverse the complete bst in inorder traversal
node=inorder(node=node->left);
node->data;
node=inorder(node-right);
if(node->data>k)
return -1;
while(node->data<=N)
node->data--; to get the one previous value of it
cout<<node->data;
}*/
/*int findMaxForN(Node* root, int N,int size)
{
if(root == NULL) return -1;
else if(root->key == N) return N;
else if(root->key < N){
int right = findMaxForN(root->right, N, size);
if(right == -1) return root->key;
}else{
return findMaxForN(root->left, N, size);
}
}*/
int findMaxForN(Node* root, int N,int size){
if(root==NULL)
return -1;
else if(root->key==N)
return N;
else if(root->key<N){
int right=findMaxForN(root->right,N,size);
if(right==-1)
return root->key;
}
else{
return findMaxForN(root->left,N,size);
}
}