Binary Search Tree Operations

#include "iostream"
#include "cstdlib"
using namespace std;

class BinarySearchTree
{
private:
struct tree_node
{
int data;
tree_node* left;
tree_node* right;
};

tree_node* root;

public:

BinarySearchTree()
{
root = NULL;
}

void Print_PreOrder();
void Print_PostOrder();
void Print_InOrder();

void inorder(tree_node*);
void preorder(tree_node*);
void postorder(tree_node*);

void insert(int);

};

void BinarySearchTree::insert(int d)
{
tree_node* current = new tree_node;
current->data = d;
current->left = NULL;
current->right = NULL;

tree_node* parent;
parent = root;

tree_node* temp;

if(root == NULL)
{
root = current;
}
else
{
while(parent)
{
temp = parent;
if(current->data > parent->data )
{
parent = parent->right;
}
else
{
parent = parent->left;
}
}

if(current->data > temp->data)
{
temp->right = current;
}
else
{
temp->left = current;
}
}


}

void BinarySearchTree::Print_PreOrder()
{
preorder(root);
}

void BinarySearchTree::preorder(tree_node* root)
{
if(root != NULL)
{
cout<<" "<data<<" ";
if(root->left)
{
preorder(root->left);
}
if(root->right)
{
preorder(root->right);
}
}
else
return;
}

void BinarySearchTree::Print_PostOrder()
{
postorder(root);
}

void BinarySearchTree::postorder(tree_node* root)
{
if(root!= NULL)
{
if(root->left)
{
postorder(root->left);
}
if(root->right)
{
postorder(root->right);
}
cout<<" "<data<<" ";
}
else
{
return;
}
}

void BinarySearchTree::Print_InOrder()
{
inorder(root);
}

void BinarySearchTree::inorder(tree_node* root)
{
if(root!= NULL)
{
if(root->left)
{
inorder(root->left);
}
cout<<" "<data<<" ";
if(root->right)
{
inorder(root->right);
}
}
else
{
return;
}
}

int main()
{
BinarySearchTree b;
int choice, value;

while(1)
{
cout< cout<<"1. Insert Creation"< cout<<"2. Inorder Traversal"< cout<<"3. Pre-Order Traversal"< cout<<"4. PostOrder Traversal"< cout<<"5. Removal"< cout<<"6. Exit"<
cout<< "Enter your choice"< cin>>choice;

switch(choice)
{
case 1: cout< cout<<"Enter the value"< cin>>value;
b.insert(value);
break;
case 2: cout< b.Print_InOrder();
break;
case 3: cout< b.Print_PreOrder();
break;
case 4: cout< b.Print_PostOrder();
break;
case 6: cout< return 0;

}

}
}

Comments

Popular posts from this blog

Network Security: LAN manager authentication level

Cisco AnyConnect Secure Mobility Client - VPN service not available. The VPN agent service is not responding