Binary search trees are binary trees where all left descendants of a node are less than the node's value and all right descendants are greater. This structure allows for efficient search, insertion, and deletion operations. The document provides definitions and examples of binary search tree properties and operations like creation, traversal, searching, insertion, deletion, and finding minimum and maximum values. Applications include dynamically maintaining a sorted dataset to enable efficient search, insertion, and deletion.
A binary search tree (BST) is a tree data structure where each node has a maximum of two children, and the values of left descendant nodes are less than the current node, which is less than the values of right descendant nodes. This structure allows for fast lookup, insertion, and removal of nodes in O(log n) time on average. However, in a worst case scenario where the tree is unbalanced, these operations can take O(n) time. Common operations on a BST include creating an empty tree, searching for a node, inserting a new node, and deleting an existing node.
This document provides information about different tree data structures including binary trees, binary search trees, AVL trees, red-black trees, splay trees, and B-trees. Binary search trees allow for fast searching and maintain an ordered structure. AVL and red-black trees are self-balancing binary search trees that ensure fast search, insert, and delete times by keeping the tree balanced. B-trees are multiway search trees that allow for efficient storage and retrieval of data in databases and file systems.
This document discusses different types of tree data structures, including binary trees and binary search trees. It provides descriptions of key tree terminology like root, parent, child, leaf nodes, and different tree traversal methods. The document also covers operations on binary search trees like insertion, searching, and deletion. It provides pseudocode examples for these BST operations and discusses handling different cases that can occur during node deletion. Finally, it briefly introduces AVL trees and the concept of balance factors and rotations needed to maintain the balanced tree property.
The document discusses binary trees and their representations and operations. It defines binary trees as trees where each node has at most two child nodes. It also defines complete binary trees as trees where every node has two children except leaf nodes. The document discusses array and linked representations of binary trees and various traversal operations like preorder, inorder and postorder traversals. It also provides code snippets for inserting and deleting nodes from a binary tree.
The document discusses data structures and algorithms related to trees. It begins by defining key terms related to trees such as root, parent, child, leaf, etc. It then discusses binary trees and binary search trees, including their representations, basic operations like search and insert, and algorithms for those operations. It also covers tree traversal methods like preorder, inorder and postorder traversal. Finally, it discusses heaps and Huffman coding.
Introduction to data structure by anil duttAnil Dutt
This document provides an introduction and overview of common data structures including linked lists, stacks, queues, trees, and graphs. It defines each structure and describes their basic operations and implementations. Linked lists allow insertions and deletions anywhere and come in singly and doubly linked varieties. Stacks and queues follow last-in, first-out and first-in, first-out rules respectively. Binary trees enable fast searching and sorting of data. Graphs represent relationships between nodes connected by edges.
The document discusses various tree traversal algorithms and operations on binary trees. It explains breadth-first traversal, depth-first traversal including preorder, inorder and postorder. It also covers searching, inserting and checking if two trees are the same in binary trees. Other topics covered include finding the size, height, root-to-leaf sums, checking if a tree is a binary search tree, and level order traversal. Iterative algorithms for postorder, preorder and inorder traversal using stacks are also presented.
This document discusses binary trees and binary search trees. It defines key terminology for trees like root, leaf, edge. It explains that a binary tree can have at most two children per node and describes traversal methods for binary trees like preorder, inorder and postorder. The document also covers constructing a binary search tree from a sorted array, inserting and deleting nodes, and applications of binary trees like file systems and network routing.
This document discusses binary search trees and efficient binary trees. It begins by explaining what a binary search tree is and how it allows for efficient searching in O(log n) time. It then discusses how to create, search, insert, delete, determine the height and number of nodes in a binary search tree. The document also covers mirrored binary trees, threaded binary trees, and AVL trees, which are self-balancing binary search trees that ensure searching remains O(log n) time.
The document defines common tree terminology and describes trees and binary trees. It discusses tree traversal methods including preorder, inorder, and postorder traversal. It also covers binary search trees, including their representation, properties, and common operations like searching, insertion, deletion, finding the minimum/maximum, and finding predecessors and successors. Key operations on binary search trees like searching, insertion, and deletion run in O(h) time where h is the tree height.
The document discusses trees and binary trees. It defines key tree terminology like nodes, edges, root, leaf, etc. It explains properties of binary trees including full, complete, and binary search trees. It describes techniques for traversing binary trees including preorder, inorder and postorder traversal using recursion and stacks. Searching and insertion operations in binary search trees are also summarized.
This document discusses binary trees and binary search trees. It defines key tree terms like root, child, parent, leaf nodes. It explains tree traversal methods like preorder, inorder and postorder. It also covers basic BST operations like insertion, search and deletion of nodes. Code snippets are provided to implement these operations and traversal methods on a sample binary search tree. Examples of traversing a sample tree in different orders are given.
This document discusses binary search trees in Python. It defines a binary search tree as a data structure where every node has at most two children, with the left child being smaller than the parent and right child being larger. It describes key properties like unique values, efficient insertion/deletion, and tree traversal flexibility. It then provides code examples for a Node class, insertion/deletion implementations, and searching a tree for a node. Finally, it discusses balancing binary search trees to maintain optimal time complexities.
A binary search tree (BST) is a binary tree where the key in each internal node is greater than or equal to any key in its left subtree and less than the key in its right subtree. The document defines BSTs and describes their basic operations like searching, inserting, deleting, and traversing nodes. It provides algorithms for each operation, such as comparing the search key to the root node then recursively searching left or right subtrees, inserting new nodes at leaf locations, and traversing trees in pre-order, in-order, and post-order sequences.
This document provides an introduction to trees as a non-linear data structure. It discusses key terms like root, parent, child, leaf nodes. It also covers different types of trees like binary trees and binary search trees. Tree traversal algorithms like preorder, inorder and postorder are explained along with pseudocode. Finally, it briefly discusses applications of trees and the Huffman algorithm for data compression.
The document discusses trees and binary search trees. It defines key tree concepts like nodes, roots, parents, children, leaves and subtrees. It explains that a binary search tree is a type of binary tree where all left descendants of a node are less than or equal to the node and all right descendants are greater. The document outlines operations on binary search trees like searching, inserting, deleting nodes and different tree traversals. It also discusses balancing binary search trees using the AVL tree data structure.
GUESS WHO'S HERE TO ENTERTAIN YOU DURING THE INNINGS BREAK OF IPL.
THE QUIZ CLUB OF PSGCAS BRINGS YOU A QUESTION SUPER OVER TO TRIUMPH OVER IPL TRIVIA.
GET BOWLED OR HIT YOUR MAXIMUM!
Ad
More Related Content
Similar to presentation 1 binary search tree in data structures.pptx (20)
The document discusses data structures and algorithms related to trees. It begins by defining key terms related to trees such as root, parent, child, leaf, etc. It then discusses binary trees and binary search trees, including their representations, basic operations like search and insert, and algorithms for those operations. It also covers tree traversal methods like preorder, inorder and postorder traversal. Finally, it discusses heaps and Huffman coding.
Introduction to data structure by anil duttAnil Dutt
This document provides an introduction and overview of common data structures including linked lists, stacks, queues, trees, and graphs. It defines each structure and describes their basic operations and implementations. Linked lists allow insertions and deletions anywhere and come in singly and doubly linked varieties. Stacks and queues follow last-in, first-out and first-in, first-out rules respectively. Binary trees enable fast searching and sorting of data. Graphs represent relationships between nodes connected by edges.
The document discusses various tree traversal algorithms and operations on binary trees. It explains breadth-first traversal, depth-first traversal including preorder, inorder and postorder. It also covers searching, inserting and checking if two trees are the same in binary trees. Other topics covered include finding the size, height, root-to-leaf sums, checking if a tree is a binary search tree, and level order traversal. Iterative algorithms for postorder, preorder and inorder traversal using stacks are also presented.
This document discusses binary trees and binary search trees. It defines key terminology for trees like root, leaf, edge. It explains that a binary tree can have at most two children per node and describes traversal methods for binary trees like preorder, inorder and postorder. The document also covers constructing a binary search tree from a sorted array, inserting and deleting nodes, and applications of binary trees like file systems and network routing.
This document discusses binary search trees and efficient binary trees. It begins by explaining what a binary search tree is and how it allows for efficient searching in O(log n) time. It then discusses how to create, search, insert, delete, determine the height and number of nodes in a binary search tree. The document also covers mirrored binary trees, threaded binary trees, and AVL trees, which are self-balancing binary search trees that ensure searching remains O(log n) time.
The document defines common tree terminology and describes trees and binary trees. It discusses tree traversal methods including preorder, inorder, and postorder traversal. It also covers binary search trees, including their representation, properties, and common operations like searching, insertion, deletion, finding the minimum/maximum, and finding predecessors and successors. Key operations on binary search trees like searching, insertion, and deletion run in O(h) time where h is the tree height.
The document discusses trees and binary trees. It defines key tree terminology like nodes, edges, root, leaf, etc. It explains properties of binary trees including full, complete, and binary search trees. It describes techniques for traversing binary trees including preorder, inorder and postorder traversal using recursion and stacks. Searching and insertion operations in binary search trees are also summarized.
This document discusses binary trees and binary search trees. It defines key tree terms like root, child, parent, leaf nodes. It explains tree traversal methods like preorder, inorder and postorder. It also covers basic BST operations like insertion, search and deletion of nodes. Code snippets are provided to implement these operations and traversal methods on a sample binary search tree. Examples of traversing a sample tree in different orders are given.
This document discusses binary search trees in Python. It defines a binary search tree as a data structure where every node has at most two children, with the left child being smaller than the parent and right child being larger. It describes key properties like unique values, efficient insertion/deletion, and tree traversal flexibility. It then provides code examples for a Node class, insertion/deletion implementations, and searching a tree for a node. Finally, it discusses balancing binary search trees to maintain optimal time complexities.
A binary search tree (BST) is a binary tree where the key in each internal node is greater than or equal to any key in its left subtree and less than the key in its right subtree. The document defines BSTs and describes their basic operations like searching, inserting, deleting, and traversing nodes. It provides algorithms for each operation, such as comparing the search key to the root node then recursively searching left or right subtrees, inserting new nodes at leaf locations, and traversing trees in pre-order, in-order, and post-order sequences.
This document provides an introduction to trees as a non-linear data structure. It discusses key terms like root, parent, child, leaf nodes. It also covers different types of trees like binary trees and binary search trees. Tree traversal algorithms like preorder, inorder and postorder are explained along with pseudocode. Finally, it briefly discusses applications of trees and the Huffman algorithm for data compression.
The document discusses trees and binary search trees. It defines key tree concepts like nodes, roots, parents, children, leaves and subtrees. It explains that a binary search tree is a type of binary tree where all left descendants of a node are less than or equal to the node and all right descendants are greater. The document outlines operations on binary search trees like searching, inserting, deleting nodes and different tree traversals. It also discusses balancing binary search trees using the AVL tree data structure.
GUESS WHO'S HERE TO ENTERTAIN YOU DURING THE INNINGS BREAK OF IPL.
THE QUIZ CLUB OF PSGCAS BRINGS YOU A QUESTION SUPER OVER TO TRIUMPH OVER IPL TRIVIA.
GET BOWLED OR HIT YOUR MAXIMUM!
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...parmarjuli1412
Mental Health Assessment in 5th semester Bsc. nursing and also used in 2nd year GNM nursing. in included introduction, definition, purpose, methods of psychiatric assessment, history taking, mental status examination, psychological test and psychiatric investigation
Search Matching Applicants in Odoo 18 - Odoo SlidesCeline George
The "Search Matching Applicants" feature in Odoo 18 is a powerful tool that helps recruiters find the most suitable candidates for job openings based on their qualifications and experience.
How to Configure Extra Steps During Checkout in Odoo 18 WebsiteCeline George
In this slide, we’ll discuss on how to Configure Extra Steps During Checkout in Odoo 18 Website. Odoo website builder offers a flexible way to customize the checkout process.
ITI COPA Question Paper PDF 2017 Theory MCQSONU HEETSON
ITI COPA Previous Year 2017, 1st semester (Session 2016-2017) Original Theory Question Paper NCVT with PDF, Answer Key for Computer Operator and Programming Assistant Trade Students.
How to Change Sequence Number in Odoo 18 Sale OrderCeline George
In this slide, we’ll discuss on how to change sequence number in Odoo 18 Sale Order. In Odoo, sequences are used to generate unique identifiers for records. These identifiers are often displayed as reference numbers, such as invoice numbers, purchase order numbers, or customer numbers.
As of 5/14/25, the Southwestern outbreak has 860 cases, including confirmed and pending cases across Texas, New Mexico, Oklahoma, and Kansas. Experts warn this is likely a severe undercount. The situation remains fluid, with case numbers expected to rise. Experts project the outbreak could last up to a year.
CURRENT CASE COUNT: 860 (As of 5/14/2025)
Texas: 718 (+6) (62% of cases are in Gaines County)
New Mexico: 71 (92.4% of cases are from Lea County)
Oklahoma: 17
Kansas: 54 (+6) (38.89% of the cases are from Gray County)
HOSPITALIZATIONS: 102 (+2)
Texas: 93 (+1) - This accounts for 13% of all cases in Texas.
New Mexico: 7 – This accounts for 9.86% of all cases in New Mexico.
Kansas: 2 (+1) - This accounts for 3.7% of all cases in Kansas.
DEATHS: 3
Texas: 2 – This is 0.28% of all cases
New Mexico: 1 – This is 1.41% of all cases
US NATIONAL CASE COUNT: 1,033 (Confirmed and suspected)
INTERNATIONAL SPREAD (As of 5/14/2025)
Mexico: 1,220 (+155)
Chihuahua, Mexico: 1,192 (+151) cases, 1 fatality
Canada: 1,960 (+93) (Includes Ontario’s outbreak, which began November 2024)
Ontario, Canada – 1,440 cases, 101 hospitalizations
Classification of mental disorder in 5th semester bsc. nursing and also used ...parmarjuli1412
Classification of mental disorder in 5th semester Bsc. Nursing and also used in 2nd year GNM Nursing Included topic is ICD-11, DSM-5, INDIAN CLASSIFICATION, Geriatric-psychiatry, review of personality development, different types of theory, defense mechanism, etiology and bio-psycho-social factors, ethics and responsibility, responsibility of mental health nurse, practice standard for MHN, CONCEPTUAL MODEL and role of nurse, preventive psychiatric and rehabilitation, Psychiatric rehabilitation,
Dastur_ul_Amal under Jahangir Key Features.pptxomorfaruqkazi
Dastur_ul_Amal under Jahangir Key Features
The Dastur-ul-Amal (or Dasturu’l Amal) of Emperor Jahangir is a key administrative document from the Mughal period, particularly relevant during Jahangir’s reign (1605–1627). The term "Dastur-ul-Amal" broadly translates to "manual of procedures" or "regulations for administration", and in Jahangir’s context, it refers to his set of governance principles, administrative norms, and regulations for court officials and provincial administration.
PREPARE FOR AN ALL-INDIA ODYSSEY!
THE QUIZ CLUB OF PSGCAS BRINGS YOU A QUIZ FROM THE PEAKS OF KASHMIR TO THE SHORES OF KUMARI AND FROM THE DHOKLAS OF KATHIAWAR TO THE TIGERS OF BENGAL.
QM: EIRAIEZHIL R K, THE QUIZ CLUB OF PSGCAS
2. BINARY SEARCH TREE
What is BST?
Binary Search Tree is a data structure used in computer science
for organizing and storing data in a sorted manner.
• Follows all properties of Binary tree.
• Left sub-tree<Root node
• Right sub-tree>root node
• Recursive Structure:
• Each sub-tree of a BST is itself a BST.
• This hierarchical structure allows for
efficient Searching, Insertion, and
Deletion operationson the data stored in
the tree.
3. Construction of BST
10 8 12 7 9
1.Add 10 as root: Since the tree is empty, 10 becomes
the root node.
2.Insert 8 to the left of 10: 8 is less than 10, so it is
placed in the left subtree.
3.Insert 12 to the right of 10: 12is greater than 10, so it
is placed in the right subtree.
4.Insert 6 to the left of 8: 6 is less than 10 and also less
than 8, so it is placed to the left of 8.
5.Insert 7 to the right of 8: 7 is less than 10 but greater
than 8, so it is placed to the right of 8.
4. Applications: • Efficient searching and sorting.
• Dynamic Datasets
• Used in Databases,file systems, and
applications requiring ordered data storage.
Binary tree vs Binary search tree:
5. Binary Search Tree (Array implementation)
A binary search tree (BST) can be implemented using an array, where each element in the array represents a node in the
tree.
Here is a guide to implementing a BST using an array:
Array Representation of BST
1.Root Node: The root of the tree is stored at index 0.
2.2. Left Child: For a node at index i, the left child is stored at index 2*i + 1.
3.3. Right Child: For a node at index i, the right child is stored at index 2*i + 2.
4.A NULL value indicates that the tree or subtree is empty.
Example:
Here is an example of a binary search tree and its corresponding array representation. Binary Search Tree:
10
/
5 20
/ /
3 7 15 25
6. Array Representation:
The array representing the tree is:[10, 5, 20, 3, 7, 15, 25].
1.The root node 10 is at index 0.The left child of 10, which is 5, is at index 1, and the right child of 10, which is 20, is at index 2.
2.The left child of 5, which is 3, is at index 3, and the right child of 5, which is 7, is at index 4.
3.The left child of 20, which is 15, is at index 5, and the right child of 20, which is 25, is at index 6.
Algorithm:
4.Start with an empty binary search tree.
5. Insert nodes into the binary search tree using the following steps:
6. If the tree is empty, create a new node with the given data and make it the root node.
7. Otherwise, compare the data of the new node with the data of the current node.
8.If the new node's data is less than the current node's data, insert the new node into the left subtree of the current node.
9.If the new node's data is greater than the current node's data, insert the new node into the right subtree of the current
node.
10.To display the data of all nodes, use a recursive function that traverses the binary search tree in inorder traversal:
7. 8. Start with the root node.
9. Display the data of the current node.
10. Recursively traverse the left subtree of the current node.
1.Recursively traverse the right subtree of the current node.
Code:
#include<iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;};
Node* insertNode(Node* root, int data) {
9. displayNodes(root->right); }}
int main() {
Node* root = NULL;
int arr[9]={8,3,10,1,6,14,4,7,13};
for(int i = 0; i < 9; i++) {
root = insertNode(root, arr[i]);}
displayNodes(root);}
Output
10. Traversal in binary search tree
Traversal in a Binary Search Tree (BST) :
Traversal in a Binary Search Tree (BST) refers to visiting all the nodes in a specific order. There are
three common types of tree traversals:
• In-order
• Pre-order
• Post-order
These methods differ based on the order in which they visit nodes.
Uses of traversal on BST:
Binary Search Tree (BST) traversal is essential for performing various operations on BSTs, such
as searching, inserting, deleting, and retrieving data in a specific order.
11. In-order Traversal:
Order: Left Subtree Root Right Subtree
→ →
Description:
In-order Traversal does a recursive In-order Traversal of the left subtree, visits the root node, and
finally, does a recursive In-order Traversal of the right subtree. This traversal is mainly used for
Binary Search Trees where it returns values in ascending order. What makes this traversal "in"
order, is that the node is visited in between the recursive function calls. The in-order traversal of
the BST gives the values of the nodes in sorted order. To get the decreasing order visit the right,
root, and left subtree.
Characteristic: When applied to a BST, it retrieves all the
elements in sorted (ascending) order.
Algorithm:
• Traverse all the nodes in left subtree
• Visit the root and print the data
• Traverse all the nodes in the right subtree
In-order Traversal
In-order:
1,3,4,6,7,8,10,13,14
13. Pre-order Traversal:
Order: Root Left Subtree Right Subtree
→ →
Description:
Pre-order Traversal is done by visiting the root node first, then recursively do a pre-order traversal
of the left subtree, followed by a recursive pre-order traversal of the right subtree. It's used for
creating a copy of the tree, prefix notation of an expression tree, etc. This traversal is "pre" order
because the node is visited "before" the recursive pre-order traversal of the left and right
subtrees.
Use Case: Useful for creating a copy of the tree or for prefix
expression evaluation.
Algorithm:
• Visit the root and print the data
• Traverse left subtree
• Traverse the right subtree
Pre-order Traversal
Pre-order:
8,3,1,6,4,7,10,14,13
14. Post-order Traversal:
Order: Left Subtree Right Subtree Root
→ →
Description:
Post-order Traversal works by recursively doing a Post-order Traversal of the left subtree and the
right subtree, followed by a visit to the root node. It is used for deleting a tree, post-fix notation of
an expression tree, etc. What makes this traversal "post" is that visiting a node is done "after" the
left and right child nodes are called recursively.
Use Case: Used in deleting nodes or postfix expression evaluation.
Algorithm:
• Traverse left subtree
• Traverse the right subtree
• Visit the root and print the data.
Post-order Traversal
Post-order:
1,4,7,6,3,13,14,10,8
15. Pre-order Traversal:
Post-order Traversal:
• Time complexity:
O(N), Where N is the number of nodes. Traversing a BST always requires time in all
cases (best, average, and worst).
• Space complexity :
O(h), Where h is the height of tree.
• Best Case:
Tree Shape: The traversal performance is always linear, so the "best case" is more about
ease of traversal, not faster time complexity.
• Average Case:
Tree Shape: A reasonably balanced tree.
• Worst Case:
Tree Shape: The BST is completely skewed (degenerates into a linked list).
Example: Inserting nodes in ascending or descending order without balancing results in
a "chain-like" structure.
16. Traversal Type Visit Order Common Use Cases
In-order Left Root Right
→ →
Sorted output of
BST elements
Pre-order Root Left Right
→ →
Tree cloning, prefix
expression
Post-order Left Right Root
→ →
Deletion of tree,
postfix expression
Conclusion
17. Introduction to Search in Binary Search Tree (BST):
What is Searching in a BST?
Searching in a Binary Search Tree involves looking for a specific value in a tree where each node follows a specific rule.
BST Property for Searching:
⚬ If the value is smaller than the node's value, we search the left subtree.
⚬ If the value is larger, we search the right subtree.
The search operation is efficient, especially in balanced trees, with a time complexity of O(log n).
Properties of a Binary Search Tree:
• Each node has a unique key.
• Left child contains values less than its parent node.
• Right child contains values greater than its parent node.
• No duplicate nodes are allowed in a proper BST.
Why Search in a BST?
Efficient Searching:
Searching in a Binary Search Tree (BST) is much faster compared to searching in unsorted lists or arrays.
Time Complexity (how fast or slow the search is):
• Best Case (O(1)): If the element you're looking for is the root (the first node you check), it only takes one step to find it.
• Average Case (O(log n)): If the tree is well-balanced (meaning it’s not too stretched out), you only need to check about half the tree
to find the element. This is fast.
• Worst Case (O(n)): If the tree is unbalanced (looking like a straight line or linked list), you might need to check every node in the
tree, which takes a lot of time.
18. Searching Algorithm in BST:
Searching Steps in BST:
• Start at the root node.
• If the key matches the current node's value, the search is successful.
• If the key is smaller than the current node's value, search the left subtree.
• If the key is larger, search the right subtree.
• Repeat these steps until you find the key or reach an empty subtree.
Example of Searching in BST:
CODE
#include <iostream>
using namespace std;
struct Node{
int data;
Node* left , * right;
Node(int value){
data = value;
left = right = NULL;
}
};
50
/
30 70
/ /
20 40 60 80
19. Node* searchBST(Node* root, int key){
if (root == NULL){
return NULL;
}
(root->data == key){
return root;
}
if(key < root->data)
return searchBST(root->left, key);
return searchBST(root->right, key);
}
int main(){
Node* root = new Node(50);
root->left = new Node(30);
root->right = new Node(70);
root->left->left = new Node(20);
root->left->right = new Node(40);
root->right->left = new Node(60);
root->right->right = new Node(80);
int key;
cout<<"Enter value to be searched :";
cin>>key;
Node* result = searchBST(root, key);
if(result != NULL){
cout << "Found the key: " << result->data <<
endl;
} else{
cout << "Key not found" << endl;
}
return 0;
}
OUTPUT:
20. Time Complexity of Searching in BST:
• Best Case (O(1)):
The best scenario happens when the value you're searching for is the root of the tree, so you find it immediately.
• Average Case (O(log n)):
If the tree is balanced (not too tall and not too flat), you can find your element quickly. The number of nodes you have to check
grows slowly as the tree gets bigger. This is the ideal scenario in most cases.
• Worst Case (O(n)):
In the worst scenario, the tree could be unbalanced, meaning it looks more like a list rather than a tree. In this case, you may have
to check every node one by one, which is slow as the tree grows.
Advantages of Searching in a BST:
• Faster Search:
Searching in a BST is much faster than searching in unsorted data, especially when the tree is balanced.
• Dynamic Operations:
You can add or remove data in a BST while keeping the tree sorted, making it very flexible.
Real-World Applications of BST:
• Database Search:
BSTs are used in databases to find records quickly .
• File Systems:
Operating systems use BSTs to organize files and find them quickly.
• Search Engines:
Used to index information and find web pages faster.
Conclusion:
• Searching in a Binary Search Tree helps find values quickly, especially when the tree is balanced.
• It’s an important tool used in databases, file systems, and search engines.
• Balanced BSTs make searching efficient, while unbalanced BSTs can slow things down.
21. Insertion
Algorithm:
1:Root Node
If the tree is empty (i.e., root == NULL), a new node is created and becomes the root.
2:Comparison of Data
If the inserted value is smaller than the current node's data, it will be inserted in the left
subtree. If the inserted value is larger than the current node's data, it will be inserted in the
right subtree.
3:Recursion
This process works by recursively going into the left or right subtree to insert the
data.
4:Return the Root
After each step, the root is returned to ensure that the tree structure is
maintained.
22. Code:
#include <iostream>
using namespace std;
// Structure for a BST Node
struct Node {
int data; //Holds the value of the node
Node* left; //Pointer to the left child of the node
Node* right; //Pointer to the right child of the node
// Constructor to initialize the node
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
// Create a new node
Node* createNode(int data) {
// Use new to dynamically allocate memory for the new node
Node* newNode = new Node(data);
return newNode;
}
// Insert a node into the BST
Node* insert(Node* root, int data) {
if (root == nullptr) {
return new Node(data); // Insert at empty position
}
if (data < root->data) {
root->left = insert(root->left, data); // If data is smaller, insert it into the left
subtree
} else if (data > root->data) {
root->right = insert(root->right, data); // If data is larger, insert it into the
right subtree
}
return root; // Return the root to maintain the structure of the tree
}
(10)
/
(5) (15)
/
(3) (7)
24. Deletion in binary search tree:
Algorithm
1. Start at the Root
Begin at the root node of the tree.
2. Search for the Node to Delete
If the value is smaller than the current node, go to the left subtree.
If the value is larger, go to the right subtree.
If the value matches, this is the node to delete.
3. Handle the Deletion cases
Case 1: Node has no child (Leaf Node):
Simply remove the node.
Case 2: Node has one child:
Replace the node with its child (connect the child to the node's parent).
Case 3: Node has two children:
Find the smallest value in the right subtree (or largest in the left subtree).
Replace the node's value with this value.
Then delete the smallest/largest value from its original position.
4. End
Ensure the tree remains sorted (BST property is maintained).
25. #include <iostream>
using namespace std;
const int MAX_SIZE = 15;
int tree[MAX_SIZE];
int size = 0;
void insert(int key) {
if (size >= MAX_SIZE) {
cout << "Tree is full" << endl;
return;
}
int index = 0;
while (index < MAX_SIZE) {
if (tree[index] == 0) {
tree[index] = key;
size++;
return;
} else if (key < tree[index]) {
index = 2 * index + 1;
} else {
index = 2 * index + 2;}}}
}
}
int findIndex(int key) {
int index = 0;
while (index < MAX_SIZE) {
if (tree[index] == 0) {
return -1;
}
if (tree[index] == key) {
return index;
}
26. if (key < tree[index]) {
index = 2 * index + 1;
} else {
index = 2 * index + 2;}}
return -1;
}
void deleteKey(int key) {
int index = findIndex(key);
if (index == -1) {
cout << "Key not found" << endl;
return;
}
tree[index] = 0;
size--;}
void display() {
for (int i = 0; i < MAX_SIZE; i++) {
if (tree[i] != 0) {
cout << tree[i] << " ";}}
cout << endl;}
int main() {
insert(50);
insert(25);
insert(75);
insert(60);
insert(52);
insert(70);
insert(12);
insert(30);
insert(6);
cout << "BST elements: ";
display();
deleteKey(12);
cout << "After deleting 12: ";
display();
//deleteKey(100);
return 0;}