DATE EX.
NO: 4: Implementation of a
Binary Search Tree
AIM:
To write a program for implementing Binary Search Tree.
ALGORITHM:
1. Read the search element from the user
2. Compare, the search element with the value of root node in the tree.
3. If both are matching, then display "Given node found!!!" and terminate the
function
4. If both are not matching, then check whether search element is smaller or larger
than that node value.
5. If search element is smaller, then continue the search process in left subtree.
6. If search element is larger, then continue the search process in right subtree.
7. Repeat the same until we found exact element or we completed with a leaf node
8. If we reach to the node with search value, then display "Element is found" and
terminate the function.
9. If we reach to a leaf node and it is also not matching, then display "Element not
found" and terminate the function.
PROGRAM :
#include<iostream>
using namespace std;
class BST
{
struct node
{
int data;
node* left;
node* right;
};
node* root;
node* makeEmpty(node* t)
{
if(t == NULL)
return NULL;
{
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
return NULL;
}
node* insert(int x, node* t)
{
if(t == NULL)
{
t = new node;
t->data = x;
t->left = t->right = NULL;
}
else if(x < t->data)
t->left = insert(x, t->left);
else if(x > t->data)
t->right = insert(x, t->right);
return t;
}
node* findMin(node* t)
{
if(t == NULL)
return NULL;
else if(t->left == NULL)
return t;
else
return findMin(t->left);
}
node* findMax(node* t)
{
if(t == NULL)
return NULL;
else if(t->right == NULL)
return t;
else
return findMax(t->right);
}
node* remove(int x, node* t)
{
node* temp;
if(t == NULL)
return NULL;
else if(x < t->data)
t->left = remove(x, t->left);
else if(x > t->data)
t->right = remove(x, t->right);
else if(t->left && t->right)
{
temp = findMin(t->right);
t->data = temp->data;
t->right = remove(t->data, t->right);
}
else
{
temp = t;
if(t->left == NULL)
t = t->right;
else if(t->right == NULL)
t = t->left;
delete temp;
}
return t;
}
void inorder(node* t)
{
if(t == NULL)
return;
inorder(t->left);
cout << t->data << " ";
inorder(t->right);
}
node* find(node* t, int x)
{
if(t == NULL)
return NULL;
else if(x < t->data)
return find(t->left, x);
else if(x > t->data)
return find(t->right, x);
else
return t;
}
public:
BST()
{
root = NULL;
}
~BST()
{
root = makeEmpty(root);
}
void insert(int x)
{
root = insert(x, root);
}
void remove(int x)
{
root = remove(x, root);
}
void display()
{
inorder(root);
cout << endl;
}
void search(int x)
{
root = find(root, x);
}
};
int main()
{
BST t;
t.insert(20);
t.insert(25);
t.insert(15);
t.insert(10);
t.insert(30);
t.display();
t.remove(20);
t.display();
t.remove(25);
t.display();
t.remove(30);
t.display();
return 0;
}
OUTPUT:
10 15 25 30 70
10 15 25 30 70
10 15 30 70
10 15 70
RESULT:
Thus the C++ program to Binary Search tree was written, executed and verified successfully.