0% found this document useful (0 votes)
50 views14 pages

FA22-BCS-219 - Binary Search Tree

This document describes a program that uses a binary search tree (BST) to manage employee records. Each employee record contains an ID, name, and position. The BST supports insertion, deletion, searching, and in-order traversal of employee records. The program includes Employee and EmployeeDirectory classes to implement the BST, with recursive functions for insertion, deletion, searching, and traversal.

Uploaded by

Rana Alam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views14 pages

FA22-BCS-219 - Binary Search Tree

This document describes a program that uses a binary search tree (BST) to manage employee records. Each employee record contains an ID, name, and position. The BST supports insertion, deletion, searching, and in-order traversal of employee records. The program includes Employee and EmployeeDirectory classes to implement the BST, with recursive functions for insertion, deletion, searching, and traversal.

Uploaded by

Rana Alam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Binary Search Tree

ASSIGNMENT # 4

CSC211-DATA STRUCTURE AND ALGORITHM

SUBMITTED BY:

DANISH RIASAT

SUBMITTED TO:

MR. IMRAN SHAHZAD

REGISTRATION NO.

FA22-BCS-219

Department of Computer Science

COMSATS University Islamabad, Sahiwal Campus


Binary Search Tree

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties −
• The left sub-tree of a node has a key less than or equal to its parent node's key.
• The right sub-tree of a node has a key greater than or equal to its parent node's key.

Binary Search Tree Operations

• Search − Searches an element in a tree.


• Insert − Inserts an element in a tree.
• Deletion – Delete a node in tree.
• Pre-order Traversal − Traverses a tree in a pre-order manner.
• In-order Traversal − Traverses a tree in an in-order manner.
• Post-order Travers al − Traverses a tree in a post-order manner.

Search Operation
The algorithm depends on the property of BST that if each left subtree has values below root and each
right subtree has values above the root.
If the value is below the root, we can say for sure that the value is not in the right subtree; we need to
only search in the left subtree and if the value is above the root, we can say for sure that the value is
not in the left subtree; we need to only search in the right subtree.

Algorithm:
If root == NULL
return NULL;
If number == root->data
return root->data;
If number < root->data
return search(root->left)
If number > root->data
return search(root->right)
Let us try to visualize this with a diagram.

4 is not found so, traverse through the left subtree of 8

4 is not found so, traverse through the right subtree of 3

4 is not found so, traverse through the left subtree of 6


4 is found
If the value is found, we return the value so that it gets propagated in each recursion step as shown in
the image below.
If you might have noticed, we have called return search(struct node*) four times. When we return
either the new node or NULL, the value gets returned again and again until search(root) returns the
final result.

If the value is found in any of the subtrees, it is propagated up so that in the end it is returned,
otherwise null is returned
If the value is not found, we eventually reach the left or right child of a leaf node which is NULL and
it gets propagated and returned.

Insert Operation
Inserting a value in the correct position is similar to searching because we try to maintain the rule that
the left subtree is lesser than root and the right subtree is larger than root.
We keep going to either right subtree or left subtree depending on the value and when we reach a
point left or right subtree is null, we put the new node there.

Algorithm:
If node == NULL
return createNode(data)
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;
The algorithm isn't as simple as it looks. Let's try to visualize how we add a number to an existing
BST.

4<8 so, transverse through the left child of 8

4>3 so, transverse through the right child of 8

4<6 so, transverse through the left child of 6


Insert 4 as a left child of 6
We have attached the node but we still have to exit from the function without doing any damage to the
rest of the tree. This is where the return node; at the end comes in handy. In the case of NULL, the
newly created node is returned and attached to the parent node, otherwise the same node is returned
without any change as we go up until we return to the root.
This makes sure that as we move back up the tree, the other node connections aren't changed.

Image showing the importance of returning the root element at the end so that the elements don't lose
their position during the upward recursion step.

Deletion Operation
There are three cases for deleting a node from a binary search tree.

Case I
In the first case, the node to be deleted is the leaf node. In such a case, simply delete the node from the
tree.

4 is to be deleted
Delete the node

Case II
In the second case, the node to be deleted lies has a single child node. In such a case follow the steps
below:
1. Replace that node with its child node.
2. Remove the child node from its original position.

6 is to be deleted

copy the value of its child to the node and delete the child
Final tree

Case III
In the third case, the node to be deleted has two children. In such a case follow the steps below:
1. Get the inorder successor of that node.
2. Replace the node with the inorder successor.
3. Remove the inorder successor from its original position.

3 is to be deleted

Copy the value of the in-order successor (4) to the node


Delete the inorder successor

Question #1

You are tasked with designing a program that manages a directory of employees using a
Binary Search Tree (BST). Each employee record has the following attributes: Employee
ID, Name, and Position. The program needs to support insertion, deletion, searching, and
in-order traversal operations.

#include <iostream>
using namespace std;

// Employee structure
struct Employee {
int employeeID;
string name;
string position;
Employee* left;
Employee* right;
Employee(int id, string n, string pos) : employeeID(id), name(n), position(pos), left(nullptr),
right(nullptr) {}
};

// Binary Search Tree class


class EmployeeDirectory {
private:
Employee* root;

// Helper function to insert an employee record into the BST


Employee* insertRecursive(Employee* current, int id, string name, string position) {
if (current == nullptr) {
return new Employee(id, name, position);
}

if (id < current->employeeID) {


current->left = insertRecursive(current->left, id, name, position);
} else if (id > current->employeeID) {
current->right = insertRecursive(current->right, id, name, position);
}
return current;
}

// Helper function to find the minimum node in the BST


Employee* findMin(Employee* node) {
Employee* current = node;
while (current->left != nullptr) {
current = current->left;
}
return current;
}
// Helper function to delete an employee record from the BST
Employee* deleteRecursive(Employee* current, int id) {
if (current == nullptr) {
return nullptr;
}

if (id < current->employeeID) {


current->left = deleteRecursive(current->left, id);
} else if (id > current->employeeID) {
current->right = deleteRecursive(current->right, id);
} else {
// Node to be deleted found
if (current->left == nullptr) {
Employee* temp = current->right;
delete current;
return temp;
} else if (current->right == nullptr) {
Employee* temp = current->left;
delete current;
return temp;
}

// Node with two children: Get the inorder successor (smallest in the right subtree)
Employee* temp = findMin(current->right);

// Copy the inorder successor's content to this node


current->employeeID = temp->employeeID;
current->name = temp->name;
current->position = temp->position;

// Delete the inorder successor


current->right = deleteRecursive(current->right, temp->employeeID);
}
return current;
}

// Helper function for in-order traversal


void inOrderTraversal(Employee* current) {
if (current != nullptr) {
inOrderTraversal(current->left);
cout << "Employee ID: " << current->employeeID << ", Name: " << current->name << ",
Position: " << current->position << endl;
inOrderTraversal(current->right);
}
}

public:
EmployeeDirectory() : root(nullptr) {}

// Public function to insert an employee record


void insert(int id, string name, string position) {
root = insertRecursive(root, id, name, position);
}

// Public function to delete an employee record


void remove(int id) {
root = deleteRecursive(root, id);
}

// Public function to search for an employee by ID


void search(int id) {
Employee* current = root;
while (current != nullptr) {
if (id == current->employeeID) {
cout << "Employee found - Employee ID: " << current->employeeID << ", Name: " <<
current->name << ", Position: " << current->position << endl;
return;
} else if (id < current->employeeID) {
current = current->left;
} else {
current = current->right;
}
}
cout << "Employee with ID " << id << " not found." << endl;
}

// Public function to perform in-order traversal


void traverseInOrder() {
cout << "In-order traversal:" << endl;
inOrderTraversal(root);
}
};

int main() {
EmployeeDirectory directory;
directory.insert(219, "Danish Riasat", "Hacker");
directory.insert(238, "Sajjad Irshad", "Grahpic Designer");
directory.insert(227, "Usama Abbas", "Gamer");

directory.traverseInOrder();

directory.search(219);
directory.search(242);

directory.remove(238);
directory.traverseInOrder();
return 0;
}

Output

In-order traversal:
Employee ID: 219, Name: Danish Riasat, Position: Hacker
Employee ID: 227, Name: Usama Abbas, Position: Gamer
Employee ID: 238, Name: Sajjad Irshad, Position: Grahpic Designer
Employee found - Employee ID: 219, Name: Danish Riasat, Position: Hacker
Employee with ID 242 not found.
In-order traversal:
Employee ID: 219, Name: Danish Riasat, Position: Hacker
Employee ID: 227, Name: Usama Abbas, Position: Gamer

You might also like