Creation,Insertion and search in Binary search tree
|
Download Attachment
|
#include < iostream.h> #include < conio.h> #include < malloc.h>
struct tree { struct tree *left; int info; struct tree *right; }*root,*ptr,*newnode,*par,*stack[100];
int loc=0;
void create(); void find(int); void traverse();
void main() { int i; clrscr(); for(i=0;i<5;i++) { create(); } }
void create() { int item; cout<<"\nEnter the info: "; cin>>item; find(item); if(loc==1) { traverse(); } else { newnode=(struct tree*)malloc(sizeof(struct tree)); newnode->info=item; newnode->left=NULL; newnode->right=NULL; if(par==NULL) { root=newnode; } else if(iteminfo) { par->left=newnode; } else { par->right=newnode; } traverse(); } }
void find(int item) { struct tree *save; if(root==NULL) { loc=0; par=NULL; return; } else if(item==root->info) { loc=1; ptr=root; par=NULL; return; } else if(iteminfo) { ptr=root->left; save=root; } else { ptr=root->right; save=root; }
while(ptr!=NULL) { if(item==ptr->info) { loc=1; par=save; return; } else if(iteminfo) { save=ptr; ptr=ptr->left; } else { save=ptr; ptr=ptr->right; } } loc=0; par=save; }
void traverse() { int top=0; stack[0]=NULL; ptr=root; cout<<"\nTree is:\n"; while(ptr!=NULL) { cout<info<<" "; if(ptr->right!=NULL) { top=top+1; stack[top]=ptr->right; } if(ptr->left!=NULL) { ptr=ptr->left; } else { ptr=stack[top]; top=top-1; } } getch(); }
|
|
|
|
|
Share this article
| Print |
Article read by 3135 times
|
|
|