RSS

Binary Search Tree (BST)

08 Mar

Binary Search Tree (BST)

#include<stdio.h>
#include<process.h>
#include<conio.h>
#include<malloc.h>
typedef struct node
{
int info;
struct node *left;
struct node *right;
struct node *p;
};
node *root,*deep,*x;
int n,lr;
void insert();
void op();
void kl();
void in(struct node*);
void pre(struct node*);
void post(struct node*);
void main()
{
root=NULL;
op();
}
void op()
{
int f;
printf(“\npress 1 for enter element\npress 2 for left rotation\npress 3 for print preorder\n press 4 for exit”);
scanf(“%d”,&f);
switch(f)
{
case 1:kl();
break;
case 2:leftrotate();
break;
case 3:pre(root);
break;
case 4:exit(1);
default : op();
break;
}
}
void kl()
{
printf(“enter element”);
scanf(“%d”,&n);
if(root==NULL)
{
root=(node*)malloc(sizeof(node));
root->info=n;
root->left=NULL;
root->right=NULL;
root->p=NULL;
}
else
{
deep=root;
insert();
}
op();
}
void insert()
{
node *ptr,*rtf;
ptr=(node*)malloc(sizeof(node));
ptr->info=n;
if(n<deep->info)
{
while(deep->left!=NULL)
{
rtf=deep->left;
if(rtf->info<ptr->info)
break;
deep=deep->left;
}
if(deep->left==NULL)
{
ptr->left=NULL;
ptr->right=NULL;
deep->left=ptr;
}
else if(rtf->info<ptr->info)
{
deep=deep->left;
insert();
}
}
else if(n>deep->info)
{
while(deep->right!=NULL)
{
rtf=deep->right;
if(rtf->info>ptr->info)
break;
deep=deep->right;
}
if(deep->right==NULL)
{
ptr->left=NULL;
ptr->right=NULL;
deep->right=ptr;
ptr->p=deep;}
else if(rtf->info>ptr->info)
{
deep=deep->right;
insert();
}
}
op();
}
void pre(struct node *root)
{
if(root!=NULL)
{
printf(“%d\t”,root->info);
pre(root->left);
pre(root->right);
}
}
Advertisements
 
Leave a comment

Posted by on March 8, 2011 in C/C++

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: