An example of tree structures

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

class tree {
public:
void insert();
void inorder(tree *);


void deletv();
private:
int y;
tree *left;
tree *right;
};

tree * root = NULL;






void tree::deletv(){
tree *c = root, *p = NULL;
int n;
if(root == NULL)
cout <<"Tree is empty ";
else{
cout << "Enter a value you want delete: ";
cin >> n;
while (c!=NULL && c->y != n){
if(n>c->y){
p = c;
c = c->right;
}
else{
p = c;
c=c->left;
}
}
if(c == NULL)
cout <<"\nValue is not found";
else{
if(c->right == NULL && c->left == NULL && p != NULL && c->y < p->y){
p->left = NULL;
delete (c);
}
else if(c->right == NULL && c->left == NULL && p != NULL && c->y > p->y){
p->right = NULL;
delete (c);
}
else if(c->left != NULL && c->right == NULL){
if(c->y < p->y){
p->left = c->left;
delete(c);
}
else{
p->right = c->left;
delete(c);
}
}//end of elseif
else if(c->right != NULL && c->left == NULL){
if(c->y < p->y){
p->left = c->right;
delete(c);
}
else{
p->right = c->right;
delete(c);
}
}//end of elseif
else if(c->right != NULL && c->left != NULL && p != NULL){
if(c->y < p->y){
p->left = c->right;
tree *t = p->left; // or c->right
while(t->left != NULL) t = t->left;
t->left = c->left;
delete (c);
}
else{
p->right = c->right;
tree *t = p->right; // or c->right
while(t->left != NULL) t = t->left;
t->left = c->left;
delete (c);
}
}//end of elseif
else if(c->left == NULL && c->right == NULL && p == NULL){
root = NULL;
delete(c);
}//end of elseif
else if(root->y == n){
tree *t = root->right;
while(t->left != NULL) t = t->left;
t->left = root->left;
root = root->right;
delete (c);
}//end of if else
cout <<"\nValue is deleted";
}//end of else
}//end of else
}//end of function deletv


void tree::inorder(tree *root){
if(root!=NULL){
inorder(root->left);
cout << root->y << " " ;
inorder(root->right);
}
}


void tree::insert(){
bool done = false;
tree *c = root;
tree *node = new tree;
cout << "Enter a value: ";
cin>> node->y;
node->left = NULL;
node->right = NULL;

if(root==NULL)root = node;
else
while (!done){
if(node->y < c->y){
if(c->left!=NULL)
c=c->left;
else{
c->left=node;
done = true;
}
}
else{
if(c->right!=NULL)
c=c->right;
else {
c->right=node;
done = true;
}
}
}
}

void main(void ){
tree k;
int x;
start : // lable
clrscr();
cout << "\n\n\n==== Main Menu ====\n\n\n";
cout << " 1- Insert a value into a tree \n";
cout << " 2- Print tree Postorder \n";
cout << " 3- Delete an item \n";
cout << " 4- Exit \n\n\n";
cout <<" Enter your choose: " ;
cin>>x;
switch (x){
case 1:
clrscr();
k.insert();
break;
case 2:
clrscr();
k.inorder(root);
getch();
break;


case 3:
clrscr();
k.deletv();
getch();
break;
case 4:
exit(0);
break;
default : ;
}

goto start;

}
Topic archived. No new replies allowed.