Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // main.c
- // trees
- //
- // Created by Mahmoud ElMarakshy on 4/28/13.
- // Copyright (c) 2013 Mahmoud ElMarakshy. All rights reserved.
- //
- #include<stdio.h>
- #include<stdio.h>
- struct node{
- char * data;
- struct node *left;
- struct node *right;
- }*root=NULL,*temp;
- struct node* insert(struct node *root,char x[]);
- struct node * delete(struct node*ptr,char a[]);
- void traverse(struct node*ptr);
- struct node * Findmin(struct node*ptr);
- void search(struct node *root,char x[]);
- int main(){
- int choice;
- char a[10];
- printf("enter choice(1 to insert , 2 insert delet , 3 traverse ):");
- scanf("%d",&choice);
- while(choice!=-1){
- switch (choice) {
- case 1:
- printf("enter data:");
- scanf("%s",a);
- root=insert(root,a);
- break;
- case 2:
- printf("enter data:");
- scanf("%s",a);
- delete(root,a);
- break;
- case 3:
- traverse(root);
- break;
- case 4:
- printf("enter data:");
- scanf("%s",a);
- search(root,a);
- default:
- break;
- }
- printf("enter choice:");
- scanf("%d",&choice);
- }
- }
- struct node * insert(struct node *root, char x[])
- {int a;
- if(!root)
- {
- root=(struct node*)malloc(sizeof(struct node));
- root->data = x;
- root->left = NULL;
- root->right = NULL;
- printf("1\n");
- return(root);
- }
- if((a=strcmp(root->data,x))>0){
- root->left = insert(root->left,x);
- }
- else
- {
- if(strcmp(root->data,x)<0)
- root->right = insert(root->right,x);
- }
- return(root);
- }
- void traverse(struct node*ptr){
- if(ptr!=NULL){
- traverse(ptr->left);
- printf("%s",ptr->data);
- traverse(ptr->right);
- }
- }
- struct node * delete(struct node*T,char a[])
- {
- if(T==NULL) ; // element is not found in the tree
- else if(strcmp(a,T->data)<0)
- T->left = delete(T->left,a);
- else if(strcmp(a,T->data)>0)
- T->right = delete(T->right,a);
- else if((T->left)!=NULL && (T->right)!=NULL) { // node with 2 children
- temp = Findmin(T->right);
- T->data = temp->data;
- T->right = delete(T->right,T->data); }
- else {
- temp = T;
- if(T->left==NULL)
- T = T->right;
- else if(T->right==NULL)
- T = T->left;
- // free(temp);
- }
- return T; }
- struct node * Findmin(struct node*ptr){
- if((ptr->left)==NULL){
- printf("min is :%s",ptr->data);
- return ptr;
- }
- else
- return Findmin(ptr->left);
- }
- void search(struct node *ptr,char x[])
- {
- while (ptr!=NULL) {
- if(strcmp(x,ptr->data)==0){
- printf("found data is :%s\n",ptr->data);
- return;
- }
- else{
- if(strcmp(x,ptr->data)<0)
- ptr=ptr->left;
- else
- ptr=ptr->right;
- }
- }
- printf("not found\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement