Binary Search Tree And Other Problems

/*include header files*/
int ar[1000];
struct bin_tree
{
int data;
struct bin_tree *left;
struct bin_tree *right;
}*root,*nd;
struct bin_tree * create_bin_tree(struct bin_tree *node,int d)
{
if(node==NULL)
{
nd=new(struct bin_tree);
nd->data=d;
nd->left=nd->right=NULL;
return nd;
}
else
{
if(d<=node->data)
node->left=create_bin_tree(node->left,d);
else
node->right=create_bin_tree(node->right,d);
return node;
}
}
void display_tree(struct bin_tree *node)
{
if(node==NULL)
return;
display_tree(node->left);
cout<<"-"<data<<"-"; display_tree(node->right);
}
int depth(struct bin_tree *node)
{
if(node==NULL)
return 0;
else
{
int left=depth(node->left);
int right=depth(node->right);
if(left>right)return (left+1);
else return (right+1);
}
}
void printpath(int ar[],int size)
{
for(int i=0;idata;
size++;
if((node->left==NULL)&&(node->right==NULL))
printpath(ar,size);
else
{
ppath(node->left,ar,size);
ppath(node->right,ar,size);
}
}
void mirror(struct bin_tree *node)
{
if(node==NULL)
return;
else
{
struct bin_tree *temp;
temp=node->left;
node->left=node->right;
node->right=temp;
mirror(node->left);
mirror(node->right);
}
}
void main()
{
int i,sel,num,d;
clrscr();
cout<<"\n(1) Create Binary search tree\n(2) Display\n(3) Count\n(4) Possible Path to leaf\n(5) Change to mirror image\n(6) Exit"; while(1){ cout<<"\nEnter your choice:"; cin>>sel;
switch(sel)
{
case 1:
cout<<"\nEnter number of nodes:"; cin>>num;
if(num>0)
{
i=0;
root=new(struct bin_tree);
cout<<"Enter node "<<(i+1)<<" data:"; cin>>d;
root->data=d;
root->left=root->right=NULL;
for(i=1;i>d;
create_bin_tree(root,d);
}
}
break;
case 2:
if(root==NULL)cout<<"\nTree is empty";
display_tree(root);
break;
case 3:
cout<<"\nDepth of the tree:"< break;
case 4:
ppath(root,ar,0);
break;
case 5:
mirror(root);
break;
case 6:
exit(0);
default:
cout<<"\nInvalid selection try again";
}}
}

Comments

Popular Posts