Me At MINERVA

Me At MINERVA

THE PHOENIX LEGION

THE PHOENIX LEGION

Facebook Badge

Friday, May 13, 2016

Binary Tree

#include
#include
using namespace std;
struct tree
{
int n;
tree *left, *right;
}*root, *current, *temp,;
void insertion(int n)
{
if (root == NULL)
{
root = new tree;
root->n = n;
root->left = root->right = NULL;
}
else{
current = root;
while (current != NULL)
{
if (n >= current->n)
{
temp = current;
current = current->right;
}
else
{
temp = current;
current = current->left;
}
}
if (n >= temp->n)
{
current = new tree;
current->n = n;
current->left =current->right= NULL;
temp->right=current;
}
else{
current = new tree;
current->n = n;
current->right = current->left=NULL;
temp->left=current;
}

}
}
void search(int n)
{
if (root == NULL)
{
cout << "empty \n";
}
else{
current = root;
while (current != NULL)
{

if (current->n == n)
{
break;
}
if (n > current->n)
{
current = current->right;
}
if (n < current->n)
{
current = current->left;
}
}
if (current == NULL)
{
cout << "OOPS! NOT FOUND \n";
}
else
{
if (current->n == n)
{
cout << "Yaaayyy! Found \n";
}
}
}
current=NULL;

}
void remove(int n)
{
if (root == NULL)
{
cout << "empty \n";
}
else{
current = root;
while (current != NULL)
{

if (current->n == n)
{
break;
}
if (n > current->n)
{
current = current->right;
}
if (n < current->n)
{
current = current->left;
}
}
if (current == NULL)
{
cout << "OOPS! NOT FOUND\n";
}
else
{
if ((current->left == NULL) && (current->right == NULL))
{
delete current;
current = NULL;
}
if (current->left = NULL)
{
temp = current;
current = current->right;
delete temp;

}
if (current->right = NULL)
{
temp = current;
current = current->left;
delete temp;
}
else{
   temp=current;
    while(current->left != NULL){
     current= current->left;}
       current->n = temp->n;
                  remove(current->n);
}
}}
}
int preorder(tree *head)
{
    if(head==NULL){
        return 0;}
    cout << head->n<<"  ";
preorder(head->left);
preorder(head->right);
}
int inorder(tree *head)
{
    if(head==NULL){
        return 0;}
preorder(head->left);
cout << head->n<<"  ";
preorder(head->right);}
int postorder(tree *head)
{
    if(head==NULL){
        return 0;}
preorder(head->left);
preorder(head->right);
cout << head->n<<"  ";}


int main()
{
   int x, y, o, z;
do
{
system("CLS");
system("COLOR F0");
cout << "1..INSERTION \n";
cout << "2.. DELETION \n";
cout << "3.. SEARCH \n";
cout << "4..DISPLAY \n";
cin >> x;
switch (x)
{
case 1:{
cout << "ENTER NUMBER \n";
cin >> y;
insertion(y);
break;
}
case 2:
{
cout << "ENTER A NUMBER \n";
cin >> z;
remove(z);
break; }
case 3:{
cout << "ENTER A NUMBER /n";
cin >> z;
search(z);
break;
}
case 4:{
if (root == NULL){
cout << "THE TREE IS EMPTY \n";}
else
{
   cout< inorder(root);
cout<
postorder(root);
cout< preorder(root);
}
break;
}
}
cout << "PRESS 1..FOR MORE OPERATIONS \n";
cin >> o;
} while (o == 1);
    return 0;
}

No comments:

Post a Comment