0% found this document useful (0 votes)
17 views21 pages

Binary Search Trees

The document provides an overview of Binary Search Trees (BSTs), covering their definition, types, operations (searching, deleting, and inserting nodes), and applications in various fields such as data management and game development. It also details traversal methods (preorder, postorder, and inorder) and discusses the advantages and disadvantages of using BSTs. Additionally, it includes references for further reading on the topic.

Uploaded by

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

Binary Search Trees

The document provides an overview of Binary Search Trees (BSTs), covering their definition, types, operations (searching, deleting, and inserting nodes), and applications in various fields such as data management and game development. It also details traversal methods (preorder, postorder, and inorder) and discusses the advantages and disadvantages of using BSTs. Additionally, it includes references for further reading on the topic.

Uploaded by

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

Binary Search Trees

 Introduction
 Types of Binary Search Trees
 Traversals
 Binary Search Trees Operations
 Application Of Binary Trees
 Advatages and Disadvantages
Group 8
1. Natasha C Kanyungwe N02422855A
2. Laura Mkandla N02418635V
3. Trevor Moyo N02418878S
4. Honest Tshuma N02419879W
5. Ayanda C Mhlanga N02421204X
6. Blessing Mhlanga N02420768F
7. Patrice Kasere N02422708B
8.Mcvey Anesuishe Shayachimwe N02428574W
9. Priatah Mukuche N02418666B
10. Fortune T Sithole N02419127M
INTRODUCTION IN BINARY SEARCH TREES
What is a Binary Search Tree?
A binary search tree includes nodes arranged in a predetermined sequence. The value of the root in a binary
search tree is higher than the value of the nodes in the left sub-tree. Meanwhile, the root’s value usually equals
or exceeds all the nodes in the right subtree.
The Anatomy of Binary Search Trees

The different components of a binary search tree in the data structure are as follows:

Nodes: Node refers to a termination point in any binary search tree in data structures.
Roots: The node on top of a binary tree is called the root.
Leaf Node: The external nodes with no child are called the leaf nodes.
Internal Node: All inner nodes with at least one child node are called internal nodes.
Parent: Apart from the root, all other nodes of the binary tree with a minimum of one subnode are a parent.
Child: The node rising straight from the parent node is the child.
Edge: An edge can indicate a relationship between two nodes by connecting them.
Depth/ Height of a Tree: The root or tree height signifies the highest number of edges from the farthest lead
node to the edges.
The different types of binary search trees

1.Balanced binary tree: In a balanced binary search tree,


the height of the right and left subtrees of a node don’t differ
by more than 1.
1. Full binary tree: Each node in a full binary tree has two or zero children.
• 3. Complete binary tree: In a complete binary search
tree, all tree levels, except for the lowest one, are
occupied by nodes.
• 4. Perfect binary tree: The internal nodes of a perfect
binary tree have a maximum of two children. Moreover,
every lead node remains at the same level within the tree.
• 5. Degenerate binary tree: In a degenerate or
pathological binary tree, every node has a single child. A
degenerate tree is a binary tree in data structure in which
each parent node has only one child node associated with
it
BINARY SEARCH OPERATIONS
Search for a Value in a Binary Search Trees

Searching for a value in a BST is very similar to how we found a value using Binary Search on an array.
For Binary Search to work, the array must be sorted already, and searching for a value in an array can then be done
really fast.

How it works:

Start at the root node.


If this is the value we are looking for, return.
If the value we are looking for is higher, continue searching in the right subtree.
If the value we are looking for is lower, continue searching in the left subtree.
If the subtree we want to search does not exist, depending on the programming language, return None, or NULL, or
something similar, to indicate that the value is not inside the BST.
Program to implement Searching
#include <stdio.h> // Driver Code
#include <stdlib.h> int main()
{
struct Node { // Creating a hard coded tree for keeping
int key; // the length of the code small. We need
struct Node* left; // to make sure that BST properties are
struct Node* right; // maintained if we try some other cases.
}; struct Node* root = newNode(50);
// Constructor to create a new BST node root->left = newNode(30);
struct Node* newNode(int item) root->right = newNode(70);
{ root->left->left = newNode(20);
struct Node* temp root->left->right = newNode(40);
= (struct Node*)malloc(sizeof(struct Node)); root->right->left = newNode(60);
temp->key = item; root->right->right = newNode(80);
temp->left = temp->right = NULL;
return temp; printf(search(root, 19) != NULL ? "Found\n"
} : "Not Found\n");
printf(search(root, 80) != NULL ? "Found\n"
// function to search a key in a BST : "Not Found\n");
struct Node* search(struct Node* root, int key)
{ return 0;
// Base Cases: root is null or key is }
// present at root
if (root == NULL || root->key == key)
return root;

// Key is greater than root's key


if (root->key < key)
return search(root->right, key);

// Key is smaller than root's key


return search(root->left, key);
}
Delete a Node in a Binary Search Tree
To delete a node, our function must first search the BST to find it.
After the node is found there are three different cases where deleting a node must be done differently.

Leaf Node: Simply remove the node.


One Child: Replace the node with its child.
Two Children: Replace the node with its inorder successor (smallest node in the right subtree) and delete the successor

How it works:
If the node is a leaf node, remove it by removing the link to it.
If the node only has one child node, connect the parent node of the node you want to remove to that child node.
If the node has both right and left child nodes: Find the node's in-order successor, change values with that node, then
delete it.
Program to Implement Deleting
def delete(node, data):

if not node:
return None
if data < node.data:
node.left = delete(node.left, data)
elif data > node.data:
node.right = delete(node.right, data)
else:
# Node with only one child or no child
if not node.left:
temp = node.right
node = None
return temp
elif not node.right:
temp = node.left
node = None
return temp
# Node with two children, get the in-order successor
node.data = minValueNode(node.right).data
node.right = delete(node.right, node.data)
return node
Insertion in Binary Tree
• Inserting elements means add a new node into the binary tree. We would first creates a root node in case of empty
tree. Then subsequent insertions involve iteratively searching for an empty place at each level of the tree. When an
empty left or right child is found then new node is inserted there. By convention, insertion always starts with the left
child node

Insertion Process
• Begin at the root node
• Compare the value to be inserted with the current node’s value
if the value is less, move to the left child
If the value is greater, move to the right child
• Repeat this process until you find an empty spot (a null child) where the new value can be inserted as a new
node
Steps for insertion

1. Start the root: check if the tree is empty. If it is, create a new node and make it the root
2. Traverse the tree(visiting all nodes of the binary search tree): depending on comparison, move left or right
3. Insert the node: when a null position is found, insert the new node
Program to Implement Insertion
Using Python
else:
if data < node.data:
node.left = insert(node.left, data)
elif data > node.data:
node.right = insert(node.right, data)
return node
Application of Binary Search Trees
Binary Search Trees (BSTs) are a fundamental data structure in computer science with a wide range of applications due to their efficient search, insertion, and deletion operations (average time
complexity of O(log n)). Below are some key applications of BSTs:

1. Searching and Retrieval


- BSTs are primarily used for efficient searching and retrieval of data.
- Example: Searching for a specific element in a sorted dataset (e.g., dictionaries, phone books).
2. Sorting
- An in-order traversal of a BST yields elements in sorted order.
- Example: Sorting a list of numbers or strings.
3. Dynamic Data Management
- BSTs are ideal for managing dynamic datasets where data is frequently inserted or deleted.
- Example: Maintaining a database of records that need frequent updates.
4. Range Queries
- BSTs can efficiently find all elements within a specific range.
- Example: Finding all employees with salaries between $50,000 and $100,000.
5. Auto-Completion and Suggestions
- BSTs are used in auto-completion systems (e.g., search engines, text editors).
- Example: Suggesting words or phrases as a user types.
6. Priority Queues
- BSTs can be used to implement priority queues, where elements are retrieved based on their priority (e.g., minimum or maximum value).
- Example: Task scheduling in operating systems.
7. Symbol Tables
- BSTs are used in compilers and interpreters to store and manage variables, functions, and other symbols.
- Example: Storing variable names and their memory addresses in a compiler.
8. Database Indexing
- BSTs are used in databases to index data for faster retrieval.
- Example: Indexing a column in a relational database to speed up query execution.
9. Game Development
- BSTs are used in game development for spatial partitioning and collision detection.
- Example: Organizing game objects in a 2D or 3D space.
10. File Systems
- BSTs are used in file systems to organize and manage directories and files.
- Example: Storing and retrieving file names in a hierarchical structure.
11. Networking and Routing
- BSTs are used in networking algorithms for efficient routing and IP address lookup.
- Example: Storing IP addresses in a routing table for quick lookup.
12. Balanced BSTs for Advanced Applications
- Balanced BSTs (e.g., AVL trees, Red-Black trees) are used in more advanced applications where maintaining balance is critical.
- Example: Implementing associative arrays (e.g., std::map in C++).
13. Machine Learning
- BSTs are used in decision tree algorithms, which are a fundamental component of machine learning models.
- Example: Building decision trees for classification and regression tasks.
14. Geometric Algorithms
- BSTs are used in computational geometry for solving problems like nearest neighbor search and range searching.
- Example: Finding the closest pair of points in a 2D plane.
15. Time-Based Scheduling
- BSTs can be used to schedule events based on time.
- Example: Scheduling tasks in a real-time system.
Traversals in Binary Search Trees
In Binary Search there are three types of Traversals

1. Preorder traversal is a tree traversal technique where the current node is visited first, followed by its left subtree, and then its right subtree.

How Does Preorder Traversal Work?

1. Visit the current node: Process the current node's value.


2. Traverse the left subtree: Recursively traverse the left subtree.
3. Traverse the right subtree: Recursively traverse the right subtree.

Example:
Suppose we have the following binary tree:

4
/ \
2 6
/ \ / \
135 7

The preorder traversal of this tree would be:

4, 2, 1, 3, 6, 5, 7
Postorder traversal
Postorder traversal is a tree traversal technique where the left subtree and the right subtree are visited first, followed by the current node.

How Does Postorder Traversal Work?

1. Traverse the left subtree: Recursively traverse the left subtree.


2. Traverse the right subtree: Recursively traverse the right subtree.
3. Visit the current node: Process the current node's value.

Example:
Suppose we have the following binary tree:

4
/ \
2 6
/\ /\
13 5 7
The postorder traversal of this tree would be:
1, 3, 2, 5, 7, 6, 4
Inorder Traversal
Inorder traversal is a tree traversal technique where the left subtree is visited first, followed by the current node, and finally the right subtree.

How Does Inorder Traversal Work?

1. *Traverse the left subtree*: Recursively traverse the left subtree.


2. *Visit the current node*: Process the current node's value.
3. *Traverse the right subtree*: Recursively traverse the right subtree.

Example:
Suppose we have the following binary tree:

4
/ \
2 6
/\ /\
13 5 7

The inorder traversal of this tree would be:


1, 2, 3, 4, 5, 6, 7
Advantage and Disadvantages
References
• https://poe.com/chat/35bec77dr4efmi0bwu4
• https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=gcse_outind
• https://www.w3schools.com/dsa/dsa_data_binarysearchtrees.php

You might also like