0% found this document useful (0 votes)
16 views10 pages

AI&DS_DSAL_Manual_4

The document outlines an assignment to implement a dictionary using a binary search tree (BST) in C++. It details the objectives, outcomes, and basic operations such as adding, deleting, and updating keywords, along with algorithms for these operations. Additionally, it includes pseudocode for creating, displaying, searching, updating, and deleting words in the dictionary.
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)
16 views10 pages

AI&DS_DSAL_Manual_4

The document outlines an assignment to implement a dictionary using a binary search tree (BST) in C++. It details the objectives, outcomes, and basic operations such as adding, deleting, and updating keywords, along with algorithms for these operations. Additionally, it includes pseudocode for creating, displaying, searching, updating, and deleting words in the dictionary.
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/ 10

ASSIGNMENT NO.

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.

 To understand operation performed on tree such as addition,


deletion, updating of keywords.

 To connect one tree to another tree

 To understand sorting of tree.

OUTCOME  Dictionary implementation using Binary Search Tree

 Various operations performed on tree

S/W PACKAGES  64-bit Open source Linux or its derivative.


AND
HARDWARE  Open Source C++ Programming tool like G++/GCC.
APPARATUS USED
REFERENCES Data structures in C++ by Horowitz, Sahni.

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

Linked list node deletion, addition, updating

Object oriented programming features

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.

 Create minimum cost spanning tree using Prim’s or Kruskal’s algorithm.

Concepts related Theory:

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.

Thus, BST divides all its sub-trees into two segments;

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.

 Insert − Inserts an element in a tree.

 Deletion − Delete 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.

2. Handling Different Deletion Scenarios:


o Once you find the node to delete, consider the following scenarios:
a. Node with No Children (Leaf Node):
 Simply remove the node from the tree by setting its parent’s appropriate child
pointer (left or right) to None.
b. Node with One Child:

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.

3. Updating the Tree:


o After deletion, ensure that the BST’s ordered property is maintained.
o If you replaced a node with a child, the BST remains ordered.
o If you replaced a node with the in-order successor or predecessor, the BST’s order is also
preserved.

PSEUDOCODE;

// Function to create a new word entry in the dictionary


FUNCTION create(STRING key, STRING meaning)
// Create a new TreeNode with the given key and meaning
TreeNode *newWord = new TreeNode(key, meaning)

// 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

// Function to display the words in ascending order


FUNCTION display_ascending(TreeNode *temp)
// If the current node is NULL, return (base case)
IF temp IS NULL THEN
RETURN
END IF

// Recursively display the left subtree


display_ascending(temp.left)

// Print the current node's key and meaning


PRINT temp.key + " : " + temp.meaning

// Recursively display the right subtree


display_ascending(temp.right)
END FUNCTION

// Function to display the words in descending order


FUNCTION display_descending(TreeNode *temp)
// If the current node is NULL, return (base case)
IF temp IS NULL THEN
RETURN
END IF

// Recursively display the right subtree


display_descending(temp.right)

// Print the current node's key and meaning


PRINT temp.key + " : " + temp.meaning

// Recursively display the left subtree


display_descending(temp.left)
END FUNCTION

// Function to search for a word in the dictionary


FUNCTION search(STRING key)
// Start from the root to search for the key
TreeNode *temp = root

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

// If the key is not found, print a message


PRINT "The word isn't present in dictionary"
END FUNCTION

// Function to update the meaning of a word or insert it if not found


FUNCTION update(STRING key)
// Start from the root to search for the key
TreeNode *temp = root

// 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

// If the key is not found, prompt the user to insert it


PRINT "The word isn't present in dictionary."

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

// Traverse the tree to find the node to delete


WHILE current is not NULL:
// Check if the current node is the one to be deleted
IF current.key == key THEN
// Case 1: The node is a leaf (no children)
IF current.left is NULL AND current.right is NULL THEN
// If the node to delete is the root
IF current == root THEN
SET root = NULL // Tree becomes empty
ELSE
// Delete the leaf node by updating parent's pointer
CALL delete_leaf_word(parent, current)
ENDIF

// Case 2: The node has a single left child


ELSE IF current.left is not NULL AND current.right is NULL THEN
// If the node to delete is the root
IF current == root THEN
SET root = current.left // Update root to its left child
ELSE
// Update parent's pointer to bypass the current node
CALL delete_singleLeftChild(parent, current)
ENDIF

// Case 2: The node has a single right child


ELSE IF current.left is NULL AND current.right is not NULL THEN
// If the node to delete is the root
IF current == root THEN
SET root = current.right // Update root to its right child
ELSE

P:F-LTL-UG/03/R1
// Update parent's pointer to bypass the current node
CALL delete_singleRightChild(parent, current)
ENDIF

// Case 3: The node has both children


ELSE
// Find the maximum node in the left subtree
SET temp = current.left
SET temp_parent = NULL // To keep track of the parent of the maximum node

// Traverse to the rightmost node in the left subtree


WHILE temp.right is not NULL:
SET temp_parent = temp // Update parent to current node
SET temp = temp.right // Move to the right child
ENDWHILE

// Replace current node's key and meaning with the maximum node's
SET current.key = temp.key
SET current.meaning = temp.meaning

// Delete the maximum node found


IF temp_parent is not NULL THEN
// If the maximum node has a parent, delete it
CALL delete_singleLeftChild(temp_parent, temp)
ELSE
// If the maximum node was the left child of current
SET current.left = temp.left // Bypass the maximum node
ENDIF

// Print success message


PRINT "The word " + key + " is deleted successfully."
RETURN // Exit the function

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

// If the loop ends, the key was not found


PRINT "The word " + key + " isn't present in the dictionary."
END FUNCTION

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

// Helper function to delete a node with a single left child


FUNCTION delete_singleLeftChild(parent, current):
// Update parent's pointer to bypass the current node
IF parent.left == current THEN
SET parent.left = current.left // Connect parent to current's left child
ELSE
SET parent.right = current.left // Connect parent to current's left child
ENDIF
DELETE current // Free memory for the current node
END FUNCTION

// Helper function to delete a node with a single right child


FUNCTION delete_singleRightChild(parent, current):
// Update parent's pointer to bypass the current node
IF parent.left == current THEN
SET parent.left = current.right // Connect parent to current's right child
ELSE
SET parent.right = current.right // Connect parent to current's right child
ENDIF
DELETE current // Free memory for the current node
END FUNCTION

Review Questions:
1. What is binary search tree?

2. How do you find the depth of a binary tree?

3. Explain pre-order and in-order tree traversal?

4. Explain implementation of deletion from a binary search tree.

P:F-LTL-UG/03/R1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy