#include#include #include #define null 0 struct bin_tree{ int value; struct bin_tree *left; struct bin_tree *right; }; typedef struct bin_tree bst; int menu(); bst *inst_bin_tree(bst *,int); bst *del(bst *,int); void display(bst *,int); void main() { bst *root=null; int num,ch; clrscr(); ch=0; while(ch!=4) { ch=menu(); switch(ch) { case 1: printf("enter the element to be inserted in the bst:\n"); scanf("%d",&num); while (num!=0) { root=inst_bin_tree(root,num); printf("enter the element to be inserted in the bst:\n"); scanf("%d",&num); } break; case 2: printf("enter the node value to be deleted:\n"); scanf("%d",&num); root=del(root,num); break; case 3:printf("displaying the bst:\n"); display(root,1); break; case 4:printf("THANK YOU FOR CHOOSING BST PROGRAME:\n"); break; default:printf("Wrong key press!\n"); break; } } getch(); } bst *inst_bin_tree(bst *root,int num) { if(root==null) { root=(bst *)malloc(sizeof(bst)); root->left=null; root->value=num; root->right=null; return(root); } else { if(num value) root->left=inst_bin_tree(root->left,num); else root->right=inst_bin_tree(root->right,num); return(root); } } bst *del(bst *root,int num) { bst *case1(bst *,bst *); bst *case2(bst *,bst *); bst *p=root,*q=null; while((p!=null)&&(p->value!=num)) { q=p; if(num value) p=p->left; else p=p->right; } if((p->right==null)||(p->left==null)) case1(p,q); else case2(p,q); return(root); } bst *case1(bst *p,bst *q) { bst *child; if((p->left==null)&&(p->right==null)) child=null; else { if(p->left!=null) child=p->left; else child=p->right; } if(q->left==p) q->left=child; else q->right=child; return(0); } bst *case2(bst *p,bst *q) { bst *ptr,*f,*suc,*parsuc; ptr=p->right; f=p; while(ptr->left!=null) { f=ptr; ptr=ptr->left; } suc=ptr; parsuc=f; case1(suc,parsuc); if(q->left==p) q->left=suc; else q->right=suc; if(p->left!=null) suc->left=p->left; else suc->right=p->right; return(0); } /*MENU*/ int menu() { int c; printf("THE BINARY SEARCH TREE PROGRAMME:\n"); printf("1->insertion\n"); printf("2->deletion\n"); printf("3->display\n"); printf("4->exit\n") ; printf("enter the choice!\n"); scanf("%d",&c); return(c); } /*display*/ void display(bst *root,int level) { int i; printf("\n"); if(root) { display(root->right,level+1); for(i=0;i value); display(root->left,level+1); } return; }
Try this code in your computer for better understanding. Enjoy the code. If you have any Question you can contact us or mail us
Post a Comment