Professional Documents
Culture Documents
Suman 3.2
Suman 3.2
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;
Output:
LEARNING OUTCOMES:
• Learned the concept of BST (Binary Search
Tree).
• Displaying BST using Post Order traversal.
• Searching technique in Binary Search Tree.