You are on page 1of 4

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment No.- 3.2

Student Name: SUMAN KUMARI UID: 21BCS4911


Branch: CSE Section/Group: 616/A
Semester: 3rd Date of Performance: 09-11-2022
Subject Name: Data Structures Subject Code: 21CSH-211

Aim: Write a program to demonstrate the implementation of different operation on a binary


search tree.

OBJECTIVE: To learn the concepts of Binary Search Tree

Algorithms:

Step 1. First compare the element to be searched with the root element of the tree.
Step 2. If root is matched with the target element, then return the node location.
Step 3. If it is not matched, then check whether the item is less than the root element, If it is
smaller than the root element then move to the left sub tree.
Step 4. If it is larger than the root element, Then move to the right sub tree.
Step 5. Repeat the above procedure recursively until the match is found.
Step 6. If the element is not found, or not present in the tree, then return null.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Program Code:

#include <iostream>
using namespace std;
class BST {
public:
int data;
BST *left = NULL, *right = NULL;
}
;
BST *insert(BST *root, int value)
{
if (!root)
{
BST *newNode = new BST();
newNode->data = value;
return newNode;
}
if (value > root->data)
{
root->right = insert(root->right, value);
}
else if (value < root->data)
{
root->left = insert(root->left, value);
}
return root;
}
BST *search(BST *root, int val)
{
if (root == NULL || root->data == val)
return root;
if (root->data < val)
return search(root->right, val);
return search(root->left, val);
}
void inorder(BST *root)
{
if (!root)
{
return;
}
inorder(root->left);
cout << root->data << endl;
inorder(root->right);
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int main()
{
int n;
cout << "enter no. of elements in a BST" << endl;
cin >> n;
BST *root = NULL;
cout << "enter elements of BST: " << endl;
for (int i = 0; i < n; i++)
{
int elem;
cin >> elem;
root = insert(root, elem);
}
cout << "Elements of BST are: " << endl;
;
inorder(root);
int val;

cout << "Enter value for search" << endl;


cin >> val;
BST *key = search(root, val);
if (key)
{
cout << "element found " << key->data;
}
else
{
cout << "sorry not in the bst" << endl;
}
return 0;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Output:

LEARNING OUTCOMES:
• Learned the concept of BST (Binary Search
Tree).
• Displaying BST using Post Order traversal.
• Searching technique in Binary Search Tree.

You might also like