Saturday, 31 December 2011

Binary Trees : Creating, Deleting and Displaying


All thanks to my friends and Khanetkar Textbook, this code finally works somehow! :D




#include<stdio.h>
#include<malloc.h>

typedef struct node
{
int info;
struct node *left, *right;
}NODE,*NODEPTR;
int count=0;

insert(int x,NODEPTR *root)
{
if((*root)==NULL)
{
(*root)=malloc(sizeof(NODE));
(*root)->left=(*root)->right=NULL;
(*root)->info=x;
count++;
return;
}
if(x<(*root)->info)
insert(x,&((*root)->left));
else
insert(x,&((*root)->right));
}

void inorder(NODEPTR root)
{
if(root!=NULL)
{
inorder(root->left);
printf("%d ",root->info);
inorder(root->right);
}
}

NODEPTR search(NODEPTR root, int num, NODEPTR *parent,int *found)
{
NODEPTR q=root,x;
*found=0;
*parent=NULL;
if(count==0)return NULL;
while(q!=NULL)//binary searching
{
if(q->info==num)
{
*found=1;
printf("Search works\n");
return q;
}
if(q->info>num)
{
*parent=q;
q=q->left;
}
else
{
*parent=q;
q=q->right;
}
}
printf("Key not found\n");
return NULL;
}

delete(NODEPTR *root, int num)
{
int found;
NODEPTR parent, x,xsucc;
if(*root==NULL)
{
printf("Tree is empty\n");
return;
}
parent=NULL;
x=NULL;
x=search(*root,num,&parent,&found);
if(!found)
{
printf("Data not found\n");
return;
}
if(x==*root&&count==1)
{
*root=NULL;
count--;
return;
}
if(x==*root&&count==2)
{
if(x->left!=NULL)
*root=x->left;
else
*root=x->right;
count--;
return;
}
if(x!=*root&&count==2)
{
(*root)->left=NULL;
(*root)->right=NULL;
count--;
return;
}
if(x->left!=NULL&&x->right!=NULL)
{
printf("Reaches correct if\n");
parent=x;
xsucc=x->right;
printf("Finds correct xsucc\n");
while(xsucc->left!=NULL)
{
parent=xsucc;
xsucc=xsucc->left;
}
x->info=xsucc->info;
x=xsucc;
printf("Successful swap\n");
}
if(x->left==NULL&&x->right==NULL)
{
if(parent->right==x)
parent->right=NULL;
else
parent->left=NULL;
free(x);
count--;
return;
}
if(x->left==NULL&&x->right!=NULL)
{
if(x==*root)
{
*root=x->right;
free(x);
count--;
return;
}
if(parent->left==x)
parent->left=x->right;
else
parent->right=x->right;
printf("Enters correct sub if\n");
free(x);
count--;
return;
}
if(x->left!=NULL&&x->right==NULL)
{
if(x==*root)
{
*root=x->left;
free(x);
count--;
return;
}
parent->left=x->left;
free(x);
count--;
return;
}
}


int main()
{
NODEPTR root=NULL;
int elt=0,cont=1,num;
printf("Enter -1 to terminate\n");
while(elt!=-1)
{
scanf("%d",&elt);
if(elt!=-1)
insert(elt,&root);
}
printf("Before deletion\n");
inorder(root);
printf("\n");
while(cont==1)
{
printf("Enter element to be deleted\n");
scanf("%d",&num);
delete(&root,num);
printf("After deletion\n");
inorder(root);
printf("\nEnter 1 to keep deleting\n");
scanf("%d",&cont);
}
}

No comments:

Post a Comment