Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<malloc.h>
- typedef struct
- {
- int data;
- struct node* left;
- struct node* right;
- }node;
- typedef struct
- {
- node* root;
- }head;
- void insert(head *t, int ele)
- {
- node *p,*q;
- q=t->root;
- p=(node*)malloc(sizeof(node));
- p->left=p->right=NULL;
- p->data=ele;
- if(t->root==NULL)
- t->root=p;
- else
- {
- while(1)
- {
- if(q->data<=(p->data)&&q->right==NULL||q->data>(p->data)&&q->left==NULL)
- break;
- if(p->data>q->data)
- q=q->right;
- else
- q=q->left;
- }
- if(q->data<=(p->data))
- q->right=p;
- else
- q->left=p;
- }
- }
- node* search(head *t,int ele)
- {
- node *q;
- q=t->root;
- while(q!=NULL)
- {
- if(q->data>ele)
- q=q->left;
- else if(q->data<ele)
- q=q->right;
- else if(q->data==ele)
- return q;
- }
- return NULL;
- }
- void inorder(node* p)
- {
- if(p==NULL)
- {
- printf("\nBinary Search Tree empty.\n");
- return;
- }
- else
- {
- inorder(p->left);
- printf("%d",p->data);
- inorder(p->right);
- }
- }
- void preorder(node* p)
- {
- if(p==NULL)
- {
- printf("\nBinary Search Tree empty.\n");
- return;
- }
- else
- {
- printf("%d",p->data);
- inorder(p->right);
- inorder(p->left);
- }
- }
- void postorder(node* p)
- {
- if(p==NULL)
- {
- printf("\nBinary Search Tree empty.\n");
- return;
- }
- else
- {
- inorder(p->left);
- inorder(p->right);
- printf("%d",p->data);
- }
- }
- void main()
- {
- int ch,ele;
- head x;
- node* y;
- x.root=NULL;
- while(1)
- {
- printf("\n1.Enter an element in the tree.\n2.Search an element\n3.Display\n4.Exit\n");
- scanf("%d",&ch);
- if(ch==4)
- break;
- switch(ch)
- {
- case 1:
- printf("\nEnter the element to be inserted\n");
- scanf("%d",&ele);
- insert(&x,ele);
- break;
- case 2:
- printf("\nEnter the element to be searched\n");
- scanf("%d",&ele);
- if(search(&x,ele))
- printf("\nElement is found.\n");
- else
- printf("\nElement is not found\n");
- break;
- case 3:
- printf("\n1.Inorder\n2.Preorder\n3.Postorder\nEnter your choice\n");
- scanf("%d",&ch);
- printf("\nEnter the element from which you want to display\n");
- scanf("%d",&ele);
- y=find(&x,ele);
- switch(ch)
- {
- case 1: inorder();
- break;
- case 2: preorder();
- break;
- case 3: postorder();
- break;
- }
- break;
- default:
- printf("\nInvalid choice\n");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement