DSA2(Unit4)
DSA2(Unit4)
man
Ra
Dr. K. Sita Ramana
Associate Professor
Department of Mathematics,
S
Malla Reddy University, Hyderabad
K
June 19, 2023
Dr
Ra
Dr. Sreenath Itikela for their assistance in gathering data, advice, and
ideas during the creation of these slides.
S
K
Dr
a
Data organisation through data structure allows for effective use
man
of the data. For instance, the clothes in our wardrobe can be
arranged in a variety of ways depending on their colour, type,
Ra
intended use, etc. Data can also be organised in multiple ways,
hence we have several data structures.
If data is arranged/accessed linearly then it is called linear data
S
structure otherwise it is called non-linear data structure.
K
Dr
a
In linear data structure, data items are arranged sequentially and
man
all data items can be traversed in a single run. But in non-linear
data structures all data items may not be traversed during a single
Ra
run as the data items are not organized sequentially.
Implementation of linear data structures is easier when compared
to non-linear data structures.
S
In linear data structures, while traversing we attain one element
at a time, hence we have only one level in it, but in non-linear
K
data structures we have multiple levels.
The different non-linear data structures are Tree, Graph.
Dr
a
man
Ra
S
K
Dr
An Example data to represent as both linear and non-linear data structures. (a)
one-sided list that does not show who works under whom (b) Represented the
relationship, so we will know the hierarchy
a
for a Tree (non-linear data structure).
man
Ra
S
K
Dr
a
the nodes, which lie in it.
man
A tree is used to represent hierarchical relationships such as parent-
child relationship.
Ra
Each node is connected to another node by directed edges.
In tree, the data elements are arranged in the hierarchical form.
Multiple runs are required to traverse through all the elements com-
S
pletely.
Each element can have multiple paths to reach another element.
K
Here elements are arranged in multiple levels, and each level can be
filled completely or partially.
Dr
a
Node: The individual element of a tree is called node.A node is any
man
structure that holds data.
Root: The topmost node of the tree from which we get all other nodes.
Ra
A tree with an undistinguishable root node cannot be considered as a
tree.
Edge: - Link connecting two nodes.
S
Parent: The node which has a branch to any other node is called a
parent or parent node. In other words it is a node which has a child.
K
Each node in a tree is a parent node.
Child: Each node that is a descendant (successor node) of another
Dr
node is called a child of that node. We can have multiple child nodes,
and these child nodes can also have their own child nodes, forming a
recursive structure.
Siblings: Nodes with same parent
Dr K S Ramana (Dept. of Maths, MRUH) DSA June 19, 2023 8 / 41
Tree - Terminology
Leaf: The nodes which does’t have child is called leaf or leaf node.
a
man
In other words a node with zero degree is called Leaf or a node in the
last/bottom-most level of the tree. It is also called external node or
terminal node.
Ra
Internal Node: Internal nodes are nodes that have one or more child
nodes. They exist between the root and the leaf nodes. In a tree other
than leafs, including root node is an internal node.
S
Path: A path in a tree is a sequence of nodes and edges. It starts
from the root and ends at a particular node in the tree.
K
Subtree: Any node of the tree along with its descendant.
Degree of a Node: The number of sub-trees of a given node or it is
Dr
the number of its child nodes. A tree consisting of only one node has
a degree of 0. This one tree node is also considered as a tree. A leaf
node has a degree of 0, while the maximum degree of a node in a tree
is the number of children it can have.
Dr K S Ramana (Dept. of Maths, MRUH) DSA June 19, 2023 9 / 41
Tree - Terminology
a
man
Degree of a Tree: It is the highest degree of a node among all the
nodes of a tree.
Ra
Level of a node: The number of edges on the path from the root
node to that node. The root node has level 0.
Height of a tree: The number of levels in a tree. The height repre-
S
sents the length of the longest path from the root to a leaf node.
Height of a Node: It is the total number of edges lies on a logest
K
path from a leaf node to the node.
Depth: The depth of a node is the number of edges from the root of
Dr
a
man
Ra
S
K
Dr
a
and edges. They have the following characteristics.
man
Root : The root node of a tree is the node that is at the very top
of the hierarchy. It is the starting point of tree’s path, and it contain
Ra
only one root node.
Nodes and Edges: A tree consists of nodes, which hold data, and
edges, which represent the connections between nodes. In a tree, if
S
we have N nodes, then we will have exactly (N-1) edges in it.
Parent and Child Nodes: Each node, except the root, has a parent
K
node to which it is directly connected. Nodes that are directly con-
nected to a parent node are called its child nodes. In a tree, every
child will have only one parent, but a parent can have multiple child
Dr
a
man
childs.
Binary Tree: It is a tree, where each node can have at most two
children. i.e., it can have either 0, or 1 or 2 children. In Binary tree
Ra
there are several types, they are
Full Binary Tree Pathological/degenerated
Complete Binary Tree Binary Tree
S
Perfect Binary Tree
Balanced Binary Tree K Skilled Binary Tree etc.,
Binary Search Tree: It is a Binary Tree, with an condition on ar-
rangement of nodes based on their key values.
AVL Tree: It consists the properties of both Binary Tree and Binary
Dr
a
man
each element in a binary tree can only have two children.
A Binary tree is represented by a pointer to the topmost node (com-
monly known as the root) of the tree. If the tree is empty, then the
Ra
value of the root is NULL. Each node of a Binary Tree contains –
Data, Pointer to the left child, Pointer to the right child.
S
K
Dr
a
structure which has the following properties:
man
The left subtree of a node contains only nodes with keys lesser
than the nodes key
The right subtree of a node contains only nodes with keys
Ra
greater than the nodes key.
The left and right subtree each must also be a binary search
tree.
S
K
Dr
a
man
Ra
S
K
Dr
a
man
Is the following tree, a Binary Search Tree.
Ra
S
K
Dr
a
man
Is the following tree, a Binary Search Tree.
Ra
X No
(because,
S
10 > 8
K and 3 < 8
etc)
Dr
a
Is the following tree, a Binary Search Tree.
man
Ra
S
K
Dr
a
Is the following tree, a Binary Search Tree.
man
Ra
X No
S
(because,
7, 5 > 2
etc)
K
Dr
a
Is the following tree, a Binary Search Tree.
man
Ra
S
K
Dr
a
Is the following tree, a Binary Search Tree.
man
Ra
S
X Yes
K
Dr
a
man
Ra
S
K
Dr
a
man
Ra
S
X Yes
K
Dr
a
difference of the left and right subtrees is less than or equal to
man
one.
Ra
S
K
Dr
As, we can see, the maximum height difference between any left and right
subtree is one. Thus this tree is an AVL Tree
a
The basic operations to manipulate the data in a tree are given below.
man
Insertion: Adding a new node to the binary tree. The insertion process
Ra
typically involves finding the appropriate position based on the binary
tree’s ordering property and adding the node as a leaf node.
Deletion: Removing a node from the binary tree. The deletion process
S
can vary depending on the specific case, such as deleting a leaf node, a
node with only one child, or a node with two children. It often requires
rearranging the tree structure to maintain its properties.
K
Search: Searching for a specific value or node in the binary tree. This
operation involves traversing the tree, comparing values, and poten-
Dr
tially moving left or right based on the comparison until the desired
value or node is found or determined to be absent.
a
man
There are different traversal techniques, including
Inorder Traversal: Visit the left subtree, visit the root node,
visit the right subtree.
Ra
Preorder Traversal: Visit the root node, visit the left subtree,
visit the right subtree.
Postorder Traversal: Visit the left subtree, visit the right
S
subtree, visit the root node.
Level-order Traversal: Visit nodes in each level from left to
K
right, starting from the root and moving down the levels.
Height and Depth Calculation: Determining the height or depth of
the binary tree. The height of a tree is the maximum number of edges
Dr
from the root to a leaf node, while the depth of a node is the number
of edges from the root to that node.
a
tree, including both internal nodes and leaf nodes.
man
Finding Minimum and Maximum: Finding the minimum or maxi-
mum value/node in the binary tree. This operation typically involves
Ra
traversing the tree in a specific order (e.g., inorder traversal for finding
the minimum value in a binary search tree).
Checking Balanced Tree: Verifying if the binary tree is balanced,
S
meaning that the heights of the left and right subtrees of each node
differ by at most 1. K
Constructing a Binary Tree: Creating a binary tree from a given set
of values or data. This operation involves building the tree structure
based on a specific algorithm or input sequence.
Dr
These are just a few common operations on binary trees. The choice of
which operations to perform depends on the requirements of the application
and the specific problem being solved using the binary tree data structure.
Dr K S Ramana (Dept. of Maths, MRUH) DSA June 19, 2023 24 / 41
Tree Traversal-Inorder,Preorder,Postorder
a
There are different methods for visiting the nodes of a tree, specially
man
Binary Tree or Binary Search Tree. These are named as Inorder, Pre-
order, Postorder and Levelorder. Among them first three are popular.
Ra
Inorder Traversal:
In inorder traversal, the left subtree is visited first, followed by
the root node, and then the right subtree (Left-Root-Right).
S
The order of visiting nodes is: left subtree → root node → right
subtree.
K
In a binary search tree, the nodes visited in inorder traversal
would be in ascending order.
Dr
a
man
left subtree, and then the right subtree (Root-Left-Right).
The order of visiting nodes is: root node → left subtree → right
subtree.
Ra
Preorder traversal is commonly used to create a copy of a binary
tree, as the root node is visited first.
Postorder Traversal:
S
In postorder traversal, the left subtree is visited first, followed by the
right subtree, and then the root node (Left-Right-Root).
K
The order of visiting nodes is: left subtree → right subtree → root
node.
Postorder traversal is often used in deleting or freeing nodes of a
Dr
a
man
1
Ra
2 3
Inorder traversal : 4 -> 2 -> 5 -> 1 -> 3
S
Preorder traversal : 1 -> 2 -> 4 -> 5 -> 3
4 5
K Postorder traversal : 4 -> 5 -> 2 -> 3 -> 1
Dr
a
man
Ra
Inorder traversal : 1 -> 3 -> 4 -> 6 -> 7 -> 8 -> 13 -> 14 -> 10
Preorder traversal : 8 -> 3 -> 1 -> 6 -> 4 -> 7 -> 10 -> 14 -> 13
S
Postorder traversal : 1 -> 4 -> 7 -> 6 -> 3 -> 13 -> 14 -> 10 -> 8
K
Dr
a
man
Ra
S
K
Dr
a
make it the root of the tree.
man
2 If the tree is not empty, traverse the tree starting from the root.
3 At each node, compare the element to be inserted with the current
node’s value.
Ra
If the element is less than the current node’s value, move to the
left subtree.
If the element is greater than the current node’s value, move to
S
the right subtree.
4 Repeat step 3 until reaching a leaf node (a node with no children) or
K
a node with a vacant child (left or right).
5 Create a new node with the given element and insert it as a child of
the leaf node or the node with a vacant child.
Dr
a
man
The deletion process is a bit more complex than insertion due to various
cases that need to be considered.
Ra
Case 1: Deleting a Leaf Node: If the node to be deleted has no
children (leaf node), simply remove the node from the tree
Case 2: Deleting a Node with One Child: If the node to be deleted
has only one child, replace the node with its child. Update the parent
S
of the node to be deleted to point to its child.
Case 3: Deleting a Node with Two Children: If the node to be
K
deleted has two children, find the node’s successor or predecessor (ei-
ther the minimum node in the right subtree or the maximum node
Dr
in the left subtree). Replace the node to be deleted with its succes-
sor/predecessor. Then, delete the successor/predecessor node from its
original position.
a
man
If the node is not found, the element does’t exist. Return the tree as
it is.
If the node is found, consider the following cases:
Ra
If the node is a leaf node, simply remove the node from the tree
by updating the parent node’s reference to it (set it to None).
If the node has only one child, bypass the node by updating the
S
parent node’s reference to point directly to the child.
If the node has two children, then:
Find the in-order successor (or in-order predecessor) of the node
K
to be deleted. This will be the node with the next smallest (or
largest) value in the tree.
Replace the node’s value with the in-order successor (or
Dr
predecessor) value.
Delete the in-order successor (or predecessor) node from its
original position using the above steps (recursive deletion).
Return the updated tree.
Dr K S Ramana (Dept. of Maths, MRUH) DSA June 19, 2023 32 / 41
Binary Search Tree - Insertion, Deletion, Searching
and Inorder traversing operations - Complete Code
a
man
[ ]: class Node:
def __init__(self, key):
self.key = key
Ra
self.left = None
self.right = None
S
# If the root is empty, create a new node and assign it as the root
return Node(key)
else:
if key < root.key:
K
# If the data is smaller than the current node, move to the
# left subtree
root.left = insert(root.left, key)
Dr
else:
root.right = insert(root.right, key)
return root
a
In [ ]: def delete_node(root, key):
man
if root is None:
# Base case: empty tree
return root
if key < root.key:
Ra
# If the key is smaller, move to the left subtree
root.left = delete_node(root.left, key)
elif key > root.key:
# If the key is larger, move to the right subtree
root.right = delete_node(root.right, key)
else:
S
# Found the node to be deleted
# Case 1: Node with no children or only one child
if root.left is None:
temp = root.right
K
root = None
return temp
elif root.right is None:
temp = root.left
Dr
root = None
return temp
# Case 2: Node with two children
temp = find_min_value_node(root.right)
root.key = temp.key
root.right = delete_node(root.right, temp.key)
return root
Dr K S Ramana (Dept. of Maths, MRUH) DSA June 19, 2023 34 / 41
Binary Search Tree - Insertion, Deletion, Searching
and Inorder traversing operations - Complete Code
a
man
[ ]: def find_min_value_node(node):
# Find the minimum value node in the subtree rooted at 'node'
Ra
current = node
while current.left is not None:
current = current.left
return current
S
def search(root, key):
if root is None or root.key == key:
# Base case: empty tree or target value found
return root
K
if key < root.key:
# If the target value is smaller, move to the left subtree
return search(root.left, key)
Dr
else:
# If the target value is larger, move to the right subtree
return search(root.right, key)
[ ]: def inorder(root):
if root:
inorder(root.left)
Dr K S Ramana (Dept. of Maths, MRUH) DSA June 19, 2023 35 / 41
return root
if key < root.key:
Binary Search Tree - Insertion, Deletion, Searching
# If the target value is smaller, move to the left subtree
return search(root.left, key)
else:
and Inorder traversing operations - Complete Code
# If the target value is larger, move to the right subtree
a
return search(root.right, key)
man
[ ]: def inorder(root):
if root:
inorder(root.left)
Ra
print(root.key, end=" ")
inorder(root.right)
def preorder(root):
if root:
S
print(root.key, end=" ")
preorder(root.left)
preorder(root.right)
K
def postorder(root):
if root:
postorder(root.left)
Dr
postorder(root.right)
print(root.key, end=" ")
a
In [ ]: # Create an empty binary search tree
man
root = None
Ra
root = insert(root, 30)
root = insert(root, 20)
root = insert(root, 40)
root = insert(root, 70)
root = insert(root, 60)
root = insert(root, 80)
S
# Print the inorder traversal of the binary search tree
print("Inorder Traversal:")
inorder(root)
K
print()
preorder(root)
print()
a
In [ ]: # Search for an element in the binary search tree
man
search_key = 60
result = search(root, search_key)
if result:
print(f"Element {search_key} found in the tree")
Ra
else:
print(f"Element {search_key} not found in the tree")
S
# Print the tree after deletion
print("Tree after deletion:")
inorder(root)
K
#OUT PUT
Inorder Traversal:
20 30 40 50 60 70 80
Dr
Preorder Traversal:
50 30 20 40 70 60 80
Postorder Traversal:
20 40 30 60 80 70 50
Element 60 found in the tree
Deleted node with key 30
Tree after deletion:
20 40 50 60 70 80
Dr K S Ramana (Dept. of Maths, MRUH) DSA June 19, 2023 38 / 41
Tree - Applications
Data Structures: Trees are fundamental data structures used in com-
a
puter science and programming. Examples include binary trees, binary
man
search trees, AVL trees, B-trees, and heaps. Trees provide efficient
storage and retrieval of data, enabling operations such as searching,
insertion, deletion, and sorting.
Ra
File Systems: File systems often use a tree structure to organize and
manage files on a computer’s storage devices. Directories and sub-
directories form a hierarchical tree, allowing efficient navigation and
S
storage of files.
Database Systems: In database systems, trees are employed for in-
K
dexing and searching data. B-trees and B+ trees are commonly used
as index structures to facilitate fast access and retrieval of data in
databases.
Dr
a
man
popular in machine learning for classification and regression tasks.
They provide interpretable models and can be combined to form more
complex ensemble models like random forests and gradient boosting.
Ra
Graph Theory: Trees are a special case of graphs without cycles.
Graph algorithms often utilize trees as a foundation for solving prob-
lems such as spanning trees, shortest paths, and network optimization.
S
Hierarchical Representations: Trees are used to represent hierarchi-
cal relationships in various applications. For instance, in organizational
K
structures, family trees, XML/HTML document structures, and file
dependency trees.
Dr
a
man
User Interface Design: Tree structures are used in the design of
user interfaces, particularly in menu systems. Hierarchical menus and
tree-like navigation structures enable users to explore and interact with
Ra
software systems.
Evolutionary Biology: Phylogenetic trees represent the evolutionary
relationships between species, showcasing the branching patterns of
S
species divergence over time. These trees aid in understanding evolu-
tionary history, biodiversity, and genetic relationships.
K
These are just a few examples of the wide range of applications where
trees are employed. The versatility and efficiency of tree structures
Dr