SlideShare a Scribd company logo
PRESENTED BY:
EESHA MAJID(2351)
AROOJ FATIMA(2344)
TAYYBA GHAFFAR(2343)
SANIA NASEEM(2352)
NOOR FATIMA(2346)
SIDRA RAFIQUE(2353)
BINARY SEARCH TREE
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.
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.
Applications: • Efficient searching and sorting.
• Dynamic Datasets
• Used in Databases,file systems, and
applications requiring ordered data storage.
Binary tree vs Binary search tree:
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
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:
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) {
if (root == NULL) {
Node* newNode = new Node();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else {
root->right = insertNode(root->right, data);}
return root;}
void displayNodes(Node* root) {
if (root != NULL) {
displayNodes(root->left);
cout << root->data << endl;
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
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.
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
Code:
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
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
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.
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
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.
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
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:
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.
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.
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)
// In-order Traversal
void inorder(Node* root) {
if (root) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
// Main Function
int main() {
Node* root = nullptr;
root = insert(root, 10);
insert(root, 5);
insert(root, 15);
insert(root, 3);
insert(root, 7);
return 0;
}
Output:
For the input 10, 5, 15, 3, 7:
In-order Traversal: 3 5 7 10 15
10
/ 
5 15
/ 
3 7
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).
#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;
}
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;}
THANK
YOU

More Related Content

PPTX
Binary Search Tree
PPTX
Binary tree
PPTX
learn tree, linked list, queue, stack, and other algo
DOCX
Biary search Tree.docx
PPTX
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
PPTX
Trees in data structure
PPTX
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
PPT
1.1 binary tree
Binary Search Tree
Binary tree
learn tree, linked list, queue, stack, and other algo
Biary search Tree.docx
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
Trees in data structure
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
1.1 binary tree

Similar to presentation 1 binary search tree in data structures.pptx (20)

PPTX
BST.pptx this isp used for learning binary search trees
PPTX
BST.pptx this is Good for data structure
PDF
Unit iv data structure-converted
PPT
Introduction to data structure by anil dutt
PPT
M.E - Computer Science and Engineering-Data structure-bst-and-threaded
PDF
Binary Tree - Algorithms
PDF
Treeeeeeeeeeeeeeeeereeeeeeeeeeeeeeee.pdf
PPTX
4. Apply data structures such as arrays, linked lists, and trees as an abstra...
PPTX
Binary tree
PPTX
Group 5-DSA.pptx........................
PDF
Trees second part in data structures with examples
PPT
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
PPT
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
PPT
Binary Search Tree
PPTX
Lec 10_Binary Search Tree in data structure and algorithm.pptx
PPT
PDF
Tree Data Structure by Daniyal Khan
PPTX
nptel 2nd presentation.pptx
PPTX
Binary search tree
PPTX
tree-160731205832.pptx
BST.pptx this isp used for learning binary search trees
BST.pptx this is Good for data structure
Unit iv data structure-converted
Introduction to data structure by anil dutt
M.E - Computer Science and Engineering-Data structure-bst-and-threaded
Binary Tree - Algorithms
Treeeeeeeeeeeeeeeeereeeeeeeeeeeeeeee.pdf
4. Apply data structures such as arrays, linked lists, and trees as an abstra...
Binary tree
Group 5-DSA.pptx........................
Trees second part in data structures with examples
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
Binary Search Tree
Lec 10_Binary Search Tree in data structure and algorithm.pptx
Tree Data Structure by Daniyal Khan
nptel 2nd presentation.pptx
Binary search tree
tree-160731205832.pptx
Ad

Recently uploaded (20)

PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Complications of Minimal Access Surgery at WLH
PDF
Classroom Observation Tools for Teachers
PDF
RMMM.pdf make it easy to upload and study
PDF
Pre independence Education in Inndia.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
GDM (1) (1).pptx small presentation for students
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
master seminar digital applications in india
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Lesson notes of climatology university.
PPTX
Cell Structure & Organelles in detailed.
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
102 student loan defaulters named and shamed – Is someone you know on the list?
Complications of Minimal Access Surgery at WLH
Classroom Observation Tools for Teachers
RMMM.pdf make it easy to upload and study
Pre independence Education in Inndia.pdf
Final Presentation General Medicine 03-08-2024.pptx
Sports Quiz easy sports quiz sports quiz
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Microbial disease of the cardiovascular and lymphatic systems
GDM (1) (1).pptx small presentation for students
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Supply Chain Operations Speaking Notes -ICLT Program
Abdominal Access Techniques with Prof. Dr. R K Mishra
master seminar digital applications in india
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Lesson notes of climatology university.
Cell Structure & Organelles in detailed.
Ad

presentation 1 binary search tree in data structures.pptx

  • 1. PRESENTED BY: EESHA MAJID(2351) AROOJ FATIMA(2344) TAYYBA GHAFFAR(2343) SANIA NASEEM(2352) NOOR FATIMA(2346) SIDRA RAFIQUE(2353) BINARY SEARCH TREE
  • 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) {
  • 8. if (root == NULL) { Node* newNode = new Node(); newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} if (data < root->data) { root->left = insertNode(root->left, data); } else { root->right = insertNode(root->right, data);} return root;} void displayNodes(Node* root) { if (root != NULL) { displayNodes(root->left); cout << root->data << endl;
  • 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
  • 12. Code:
  • 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)
  • 23. // In-order Traversal void inorder(Node* root) { if (root) { inorder(root->left); cout << root->data << " "; inorder(root->right); } } // Main Function int main() { Node* root = nullptr; root = insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 3); insert(root, 7); return 0; } Output: For the input 10, 5, 15, 3, 7: In-order Traversal: 3 5 7 10 15 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;}

Editor's Notes