-
Notifications
You must be signed in to change notification settings - Fork 493
/
CeilValue.cpp
127 lines (111 loc) Β· 2.27 KB
/
CeilValue.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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// What is Ceil value in BST ?
/* Supoose we are given a 'key' value, The Lowest value in the binary Search Tree that's greater than or equal to the key
is called Ceil Value */
#include<bits/stdc++.h>
using namespace std;
struct node{//Structure of every node of BST
int data;
struct node*left;
struct node*right;
node(int val){
data=val;
left=right=NULL;
}
};
//Insert values into BST
node* INSERTintoBST(node * root,int val){
if(root==NULL) {
return new node(val);
}
while(true){
if(root->data<=val){
if(root->right!=NULL)
{
root=root->right;
}
else{
root->right=new node(val);
break;
}
}
else{
if(root->left!=NULL){
root=root->left;
}
else {
root->left=new node(val);
break;
}
}
}
//Function to find Ceil value
int findCeil(node * root,int key){
int ceil=-1;//initial value of ceil
while(root){
if(root->data==key){// if value equal to key
ceil=root->data;
return ceil;
}
if(key> root->data){
root=root->right;
}
else{
ceil=root->data;
root=root->left;
}
}
return ceil;
}
int main(){
int nodes, val;
cout<<"enter the number of nodes"<<endl;
cin>>nodes;
cout<<"enter 1st value"<<endl;
cin>>val;
struct node*root=new node(val);
int i=nodes-1;
while(i){
cout<<"enter other values"<<endl;
cin>>val;
INSERTintoBST(root,val);
i--;
}
int key;
cout<<"enter the key"<<endl;
cin>>key;
cout<<"The Floor value in BST w.r.t to the key ->"<<endl;
cout<<findCeil(root,key);
/* OUTPUT :
enter the number of nodes
9
enter 1st value
8
enter other values
3
enter other values
10
enter other values
1
enter other values
6
enter other values
13
enter other values
14
enter other values
4
enter other values
7
enter the key
7
The Floor value in BST w.r.t to the key ->
7
8
/ \
3 10
/\ / \
1 6 13 14
/\
4 7
Lets Take the key=7 , So the Ceilr Value is =7
*/