Created
March 2, 2017 14:13
-
-
Save shubham100795/b023d8baa1b479e233a8eae0d2f3a64d to your computer and use it in GitHub Desktop.
Find ceil and floor of a key in BST
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<cstdlib> | |
using namespace std; | |
struct node{ | |
int data; | |
struct node *left; | |
struct node *right; | |
}; | |
struct node *newnode(int x) | |
{ | |
struct node* ptr=(struct node*)malloc(sizeof(struct node)); | |
ptr->data=x; | |
ptr->left=NULL; | |
ptr->right=NULL; | |
return ptr; | |
} | |
struct node* insert(struct node *root,int x) | |
{ | |
struct node* par; | |
if(root==NULL) | |
{ | |
root=newnode(x); | |
return root; | |
} | |
else | |
{ | |
struct node *proot=root; | |
while(proot!=NULL) | |
{ | |
if(x<proot->data) | |
{ | |
par=proot; | |
proot=proot->left; | |
} | |
else | |
{ | |
par=proot; | |
proot=proot->right; | |
} | |
} | |
if(x<par->data) | |
par->left=newnode(x); | |
else | |
par->right=newnode(x); | |
return root; | |
} | |
} | |
void display(struct node *root) | |
{ | |
if(root==NULL) | |
return; | |
display(root->left); | |
cout<<"\t"<<root->data; | |
display(root->right); | |
} | |
void findceilfloor(struct node *root,int &ceil,int &floor,int key) | |
{ | |
if(root==NULL) | |
return; | |
if(root->data==key) | |
{ | |
ceil=root->data; | |
floor=root->data; | |
} | |
if(key<root->data) | |
{ | |
ceil=root->data; | |
findceilfloor(root->left,ceil,floor,key); | |
} | |
if(key>root->data) | |
{ | |
floor=root->data; | |
findceilfloor(root->right,ceil,floor,key); | |
} | |
} | |
int main() | |
{ | |
int x,key; | |
int ceil=-1,floor=-1; | |
struct node *root=NULL; | |
while(1) | |
{ | |
cin>>x; | |
if(x==-1) | |
break; | |
root=insert(root,x); | |
} | |
display(root); | |
cout<<endl; | |
cin>>key; | |
findceilfloor(root,ceil,floor,key); | |
cout<<"\n ceil is "<<ceil<<" and floor is"<<floor; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment