Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the insert, delete and print functions for the following 2-3 tree: struct

ID: 674162 • Letter: W

Question

Write the insert, delete and print functions for the following 2-3 tree:

struct tree{ // A 2-3 tree

struct app_info; // Information about the application
struct tree *left; // Pointer to the left subtree
struct tree *mid; // Pointer to the middle subtree
struct tree *right; // Pointer to the right subtree
};

The struct info is:

struct app_info{

char category[ CAT_NAME_LEN ]; // Name of category
char app_name[ APP_NAME_LEN ]; // Name of the application
char version[ VERSION_LEN ]; // Version number
float size; // Size of the application
char units[ UNIT_SIZE ]; // GB or MB
float price; // Price in $ of the application
};

Explanation / Answer

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

struct tree
{
int x;
tree *left;
tree *right;
};

class btree
{
private:
tree *t;
public:
btree()
{
t=NULL;
}
tree* insert(tree* t, int a);
tree* del(tree* t,int a);
tree* findmin(tree* temp);
void LVR(tree *t);
void LRV(tree *t);
void VLR(tree *t);
void menu();
void show();
};

tree* btree::insert(tree* t,int a)
{
if(t==NULL)
{
t=new tree;
t->x=a;
t->left=NULL;
t->right=NULL;
}
else if(a<t->x)
t->left=insert(t->left,a);
else if(a>t->x)
t->right=insert(t->right,a);
return t;
}

tree* btree::del(tree* t,int a)
{
tree *temp;
if(t==NULL)
cout<<"Elements not found";
else if(a<t->x)
t->left=del(t->left,a);
else if(a>t->x)
t->right=del(t->right,a);
else if(t->left&&t->right)
{
temp=findmin(t->right);
t->x=temp->x;
t->right=del(t->right,t->x);
}
else
{
temp=t;
if(t->left==NULL)
t=t->right;
if(t->right==NULL)
t=t->left;
}
return t;
}

tree* btree::findmin(tree* temp)
{
while(temp->left)
temp=temp->left;
return temp;
}

void btree::LVR(tree *t)
{
if(t)
{
LVR(t->left);
cout<<" "<<t->x;
LVR(t->right);
}
}

void btree::LRV(tree *t)
{
if(t)
{
LRV(t->left);
LRV(t->right);
cout<<" "<<t->x;
}
}

void btree::VLR(tree *t)
{
if(t)
{
cout<<" "<<t->x;
VLR(t->left);
VLR(t->right);
}
}

void btree::menu()
{
while(1)
{
cout<<endl
<<"BINARY TREE"<<endl
<<"1.Insert"<<endl
<<"2.Delete"<<endl
<<"3.Display"<<endl
<<"4.Exit"<<endl;
int ch,a;
cout<<"Enter your choice : ";
cin>>ch;
switch(ch)
{
case 1: cout<<"Enter a value to insert : ";
   cin>>a;
   t=insert(t,a);
   break;
case 2: cout<<"Enter value to delete : ";
   cin>>a;
   t=del(t,a);
   break;
case 3: show();
   break;
case 4: exit(0);

default:cout<<"Sorry! wrong choice"<<endl;
}
}
}
void btree::show()
{
int ch1;
cout<<"1.Preorder"<<endl
<<"2.Inorder"<<endl
<<"3.Postorder"<<endl
<<"Enter your choice : ";
cin>>ch1;
switch(ch1)
{
case 1: VLR(t);
   break;
case 2: LVR(t);
   break;
case 3: LRV(t);
   break;
}
}

void main()
{
btree b;
clrscr();
b.menu();
getch();
}