Friday, April 17, 2009

TRTV

#include
#include
#include
#define newnode (tree_type *)malloc(sizeof(tree_type))
typedef struct tree
{
int info;
struct tree *left,*right;
}tree_type;
tree_type *insert(tree_type *t,int val)
{
if(t==NULL)
{
t=newnode;
t->info=val;
t->left=t->right=NULL;
}
else if(valinfo)
t->left=insert(t->left,val);
else if(val>t->info)
t->right=insert(t->right,val);
else
printf("\n Duplicate number");
return(t);
}
void preorder(tree_type *t)
{
if(t)
{
printf("%4d",t->info);
preorder(t->left);
preorder(t->right);
}
}
void inorder(tree_type *t)
{
if(t)
{
inorder(t->left);
printf("%4d",t->info);
inorder(t->right);
}
}
void postorder(tree_type *t)
{
if(t)
{
postorder(t->left);
postorder(t->right);
printf("%4d",t->info);
}
}
int menu()
{
int opt;
printf("\n 1.Create Tree\n 2. Insert Node\n 3. Delete Node\n");
printf("4.Search Item\n 5. Exit \nEnter Your Option");
scanf("%d",&opt);
return(opt);
}
int search(tree_type *t,int key)
{
if(t==NULL)
return NULL;
else if(keyinfo)
return(search(t->left,key));
else if(key>t->info)
return(search(t->right,key));
else
return(1);
}
tree_type *find(tree_type *t)
{
while(t->right!=NULL)
t=t->right;
return(t);
}
tree_type *Delete(tree_type *t,int val)
{
tree_type *temp,*child;
if(t==NULL)
printf("ELEMENT NOT FOUND");
else if(valinfo)
t->left=Delete(t->left,val);
else if(val > t->info)
t->right=Delete(t->right,val);
else if(t->left!=NULL && t->right!=NULL)
{
temp=find(t->left);
t->info=temp->info;
t->left=Delete(t->left,t->info);
}
else
{
temp=t;
if(t->left==NULL)
child=t->right;
if(t->right==NULL)
child=t->left;
free(temp);
return(child);
}
return(t);
}
void main()
{
tree_type *root=NULL ,*val;
int opt,num;
while(1)
{
clrscr();
printf("\n\n PREORDER :");
preorder(root);
printf("\n\n INORDER :");
inorder(root);
printf("\n\n POST ORDER :");
postorder(root);
opt=menu();
switch(opt)
{
case 1:printf("Enter value or 0 to end\n");
do
{
scanf("%d",&num);
if(num!=0)
root=insert(root,num);
}while(num!=0);
break;
case 2:printf("Enter the number :");
scanf("%d",&num);
root=insert(root,num);
break;
case 3:printf("Enter the number to br deleted:");
scanf("%d",&num);
root=Delete(root,num);
break;
case 4:printf("\n Enter Item to search:");
scanf("%d",&num);
if(search(root,num))
printf("Item %d Found\n",num);
else
printf("NOT FOUND");
getch();
break;
case 5:return;
}
}
}

No comments: