AI&DS_DSAL_Manual_4
AI&DS_DSAL_Manual_4
4
TITLE To write a program for implementing dictionary using binary search
tree.
PROBLEM A dictionary stores keywords and its meanings. Provide facility for
STATEMENT adding new keywords, deleting keywords, updating values of any
/DEFINITION entry. Provide facility to display whole data sorted in ascending/
descending order. Also find how many maximum comparisons may be
required for finding any keyword. Use Binary Search Tree for
implementation.
OBJECTIVE To understand Binary Search Tree implementation.
1. Date
INSTRUCTIONS 2. Assignment no.
FOR 3. Problem definition
WRITING 4. Learning objective
JOURNAL 5. Learning Outcome
6. Concepts related Theory
7. Algorithm
8. Test cases
10. Conclusion/Analysis
Assignment 2:
Aim: To write a program for Dictionary implementation using Binary Search Tree
Prerequisites:
Basic knowledge of linked list, searching
Learning Objectives:
To understand binary search tree implementation
P:F-LTL-UG/03/R1
Learning Outcomes
After successful completion of this assignment, students will be able to
Implement graph using adjacency matrix or adjacency list.
In computer science, binary search trees (BST), sometimes called ordered or sorted binary trees, are a
particular type of containers: data structures that store "items" (such as numbers, names etc.) in memory.
They allow fast lookup, addition and removal of items, and can be used to implement either dynamic sets
of items, or lookup tables that allow finding an item by its key (e.g., finding the phone number of a person
by name).
Binary search trees keep their keys in sorted order, so that lookup and other operations can use the principle
of binary search: when looking for a key in a tree (or a place to insert a new key), they traverse the tree
from root to leaf, making comparisons to keys stored in the nodes of the tree and deciding, based on the
comparison, to continue searching in the left or right subtrees. On average, this means that each comparison
allows the operations to skip about half of the tree, so that each lookup, insertion or deletion takes time
proportional to the logarithm of the number of items stored in the tree. This is much better than the linear
time required to find items by key in an (unsorted) array, but slower than the corresponding operations on
hash tables.
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 to its parent node's key.
Representation:
BST is a collection of nodes arranged in a way where they maintain BST properties. Each node has a
key and an associated value. While searching, the desired key is compared to the keys in BST and if found,
the associated value is retrieved.
Following is a pictorial representation of BST
P:F-LTL-UG/03/R1
We observe that the root node key (27) has all less-valued keys on the left sub-tree and the higher valued
keys on the right sub-tree.
Basic Operations:
Following are the basic operations of a tree −
Search − Searches an element in a tree.
Node:- Define a node having some data, references to its left and right child nodes.
Search Operation:
Whenever an element is to be searched, start searching from the root node. Then if the data is less
than the key value, search for the element in the left subtree. Otherwise, search for the element in the right
subtree. Follow the same algorithm for each node.
Algorithm:
SearchBST (root, key, LOC, PAR ){
//key is the value to be searched.
//This procedure find the location LOC of key and also the location PAR of the parent of the key.
1. If ( root == NULL) Then
1.1 Print (“Tree does not exist”)
1.2 LOC = NULL and PAR = NULL
1.3 exit
2. PAR = NULL, LOC = NULL
3. ptr = root
4. While ( ptr != NULL )
4.1 if ( key = ptr -> info ) then
4.1.1 LOC = ptr
4.1.2 print PAR AND LOC
4.1.3 exit
4.1 else if ( key < ptr -> info ) then
4.1.1 PAR = ptr
4.1.2 ptr = ptr -> left
4.1 else
4.1.1 PAR = ptr
4.1.2 ptr = ptr -> right
5. If ( LOC = NULL ) then
5.1 Print (“Key not found”)
}
Insert Operation:
Whenever an element is to be inserted, first locate its proper location. Start searching from the root node,
then if the data is less than the key value, search for the empty location in the left subtree and insert the
data. Otherwise, search for the empty location in the right subtree and insert the data.
Algorithm:
P:F-LTL-UG/03/R1
Algorithm InsertBST (root, key, LOC, PAR) { // key is the value to be inserted.
1. call SearchBST (root, key, LOC , PAR )// To find the parent PAR of the new node
2. If ( LOC != NULL)
2.1 Print “ Node already exist”
2.2 Exit
3. create a new node [new1 = new Node()]
4. new1 -> info = key
5. new1 -> left = NULL , new1 -> right = NULL
6. If ( PAR = NULL ) Then
6.1 root = new1
6.2 exit
elseif ( new1 -> info < PAR -> info)
6.1 PAR -> left = new1
6.2 exit
else
6.1 PAR -> right = new1
6.2 exit
}
Deletion:
Delete operation in a binary search tree refers to the process of deleting the specified node from
the tree.
Before implementing a delete operation, you first need to locate the position of the node to be
deleted and its parent.
To locate the position of the node to be deleted and its parent, you need to implement a search
operation.
Once the nodes are located, there can be three cases:
Case I: Node to be deleted is the leaf node
Case II: Node to be deleted has one child (left or right)
Case III: Node to be deleted has two children
Algorithm:
1. Search for the Node to Delete:
o Start at the root of the BST.
o Compare the key of the node you want to delete with the current node’s key.
o If the key matches the current node’s key, you have found the node to delete.
o If the key is less than the current node’s key, move to the left subtree.
o If the key is greater than the current node’s key, move to the right subtree.
o Repeat this process until you find the node to delete or determine that it does not exist in the
tree.
P:F-LTL-UG/03/R1
If the node has only one child (either left or right), replace the node with its child.
Update the parent’s pointer to the child node.
c. Node with Two Children:
If the node to delete has two children, you need to find its in-order successor (the
node with the smallest key in its right subtree) or in-order predecessor (the node
with the largest key in its left subtree).
Copy the in-order successor’s or predecessor’s key to the node you want to
delete.
Then, recursively delete the in-order successor or predecessor node.
PSEUDOCODE;
// If the root of the tree is NULL, set the new word as the root
IF root IS NULL THEN
root = newWord
ELSE
// Start from the root to find the correct position for the new word
TreeNode *temp = root
// Traverse the tree to find the correct position for the new word
WHILE temp IS NOT NULL DO
// If the new word's key is less than the current node's key
IF newWord.key < temp.key THEN
// If there is no left child, insert the new word here
IF temp.left IS NULL THEN
temp.left = newWord
BREAK // Exit the loop after insertion
ELSE
// Move to the left child and continue searching
temp = temp.left
END IF
ELSE
// If the new word's key is greater than or equal to the current node's key
IF temp.right IS NULL THEN
// If there is no right child, insert the new word here
temp.right = newWord
BREAK // Exit the loop after insertion
P:F-LTL-UG/03/R1
ELSE
// Move to the right child and continue searching
temp = temp.right
END IF
END IF
END WHILE
END IF
END FUNCTION
P:F-LTL-UG/03/R1
// Traverse the tree until the key is found or the end is reached
WHILE temp IS NOT NULL DO
// If the key matches the current node's key, print the meaning
IF key == temp.key THEN
PRINT temp.meaning
RETURN // Exit the function after finding the key
ELSE
// If the key is less than the current node's key, move to the left child
IF key < temp.key THEN
temp = temp.left
ELSE
// If the key is greater, move to the right child
temp = temp.right
END IF
END IF
END WHILE
// Traverse the tree until the key is found or the end is reached
WHILE temp IS NOT NULL DO
// If the key matches the current node's key, update the meaning
IF key == temp.key THEN
STRING new_meaning
PRINT "Enter the new meaning : "
INPUT new_meaning // Get the new meaning from the user
temp.meaning = new_meaning // Update the meaning
RETURN // Exit the function after updating
ELSE
// If the key is less than the current node's key, move to the left child
IF key < temp.key THEN
temp = temp.left
ELSE
// // If the key is greater, move to the right child
temp = temp.right
END IF
END IF
END WHILE
P:F-LTL-UG/03/R1
PRINT "Do you want to insert this word in dictionary (y/n)"
CHAR ch
INPUT ch // Get the user's choice
// If the user wants to insert the word, call the create function
IF ch == 'y' THEN
STRING meaning
PRINT "Enter the meaning : "
INPUT meaning // Get the meaning from the user
create(key, meaning) // Insert the new word into the dictionary
END IF
END FUNCTION
FUNCTION delete_word(key):
// Initialize pointers for traversal
SET current = root // Start from the root of the tree
SET parent = NULL // Parent of the current node
P:F-LTL-UG/03/R1
// Update parent's pointer to bypass the current node
CALL delete_singleRightChild(parent, current)
ENDIF
// Replace current node's key and meaning with the maximum node's
SET current.key = temp.key
SET current.meaning = temp.meaning
ELSE
// Move to the left or right child based on the key comparison
SET parent = current // Update parent to current node
IF key < current.key THEN
SET current = current.left // Move left
ELSE
SET current = current.right // Move right
ENDIF
ENDIF
ENDWHILE
P:F-LTL-UG/03/R1
// Helper function to delete a leaf node
FUNCTION delete_leaf_word(parent, current):
// Update parent's pointer to remove the current node
IF parent.left == current THEN
SET parent.left = NULL // Remove from left
ELSE
SET parent.right = NULL // Remove from right
ENDIF
DELETE current // Free memory for the current node
END FUNCTION
Review Questions:
1. What is binary search tree?
P:F-LTL-UG/03/R1