BINARY SEARCH TREE IMPLE MENTATION

#include<stdio.h> #include<stdlib.h> #include<conio.h> typedef struct tree *node; node insert(int,node T); void find(node T,int); node findmin(node T); node del(int,node T); void display(node T); struct tree { int data; struct tree *right,*left; }*root; void main() { node T=NULL; int data,n,i=0,x; char c; clrscr(); printf("Enter the number of elements in the tree:"); scanf("%d",&n); printf("\nEnter the elements\n"); while(i<n) { scanf("%d",&data); T=insert(data,T); i++; } printf("\nElements displayed in inorder format\n"); display(T); printf("\nEnter the element to be searched:\t"); scanf("%d",&x); find(T,x); printf("\nEnter the element to delete\n"); scanf("%d",&data); T=del(data,T); printf("\nContents of tree after deletion"); display(T); getch(); } node insert(int x,node T) { struct tree *newnode; newnode = malloc(sizeof(struct tree));
1 | Page bst coding

if(newnode==NULL) printf("Out of space\n"); else { if(T==NULL) { newnode->data=x; newnode->left=NULL; newnode->right=NULL; T=newnode; } else { if(x<T->data) T->left=insert(x,T->left); else T->right=insert(x,T->right); } } return T; } void find(node T,int x) { if(T==NULL) printf("\nSearch element not found"); else { if(T->data==x) printf("\nSearch element %d is found",x); else if(x<T->data) find(T->left,x); else find(T->right,x); } } node de l ( i n t x ,node T) { node tmpce l l ; i f ( T==NULL ) pr in t f ( " \nE lement not f ound" ) ; e l se i f ( x<T- >data ) T- >le f t=de l (x , T- >le f t ) ; e l se i f ( x>T- >data ) T- >r igh t=de l (x , T- >r igh t ) ; e l se i f ( T - >le f t&&T- >r igh t ) 2 | Page bst coding

{ tmpce l l= f indmin ( T- >r igh t ) ; T- >data=tmpce l l - >data ; T- >r igh t=de l ( T- >data , T- >r igh t ) ; } e l se { tmpce l l=T ; i f ( T - >le f t==NULL ) T=T- >r igh t ; e l se i f ( T - >r igh t==NULL ) T=T- >le f t ; f ree ( tmpce l l ) ; } re tu rn T ; } node f i ndmin (node T) { i f ( T !=NULL ) { i f ( T - >le f t==NULL ) re tu rn T ; e l se re tu rn f i ndmin ( T- >le f t ) ; } re tu rn (0 ) ; } vo id d i sp lay (node T) { i f ( T !=NULL ) { d i sp lay ( T- >le f t ) ; pr in t f ( "%d\ t " , T- >data ) ; d i sp lay ( T- >r igh t ) ; } }

3 | Page bst coding

Sign up to vote on this title
UsefulNot useful