Data Structures and Algorithm-1
Data Structures and Algorithm-1
AND
ALGORITHM
BY – PROF. JAGRUTI DANDGE
BASICS OF THE COURSE
• Course Name – Data Structure and Algorithm
• Course Code – ITOEC0010/
ITMDM5001/ITMDM6001/ ITOE0020
• Schemes -
Teaching Scheme Examination Scheme
Lectures: 3 Hrs/ Week ISE I : 15 Marks
Tutorial : 0 ISE II : 15 Marks
Credits : 3 ISE III: 10 Marks
End Semester Exam : 60 Marks
BASICS OF THE COURSE
• COURSE DESCRIPTION:
• The course covers basics of data structures
and algorithms.
• Topics covered in this course include
abstraction, stack, queues, lists, trees, and
graphs, sorting and complexity of algorithm.
• The course enables the students to design
good efficient solutions to real world
problems.
BASICS OF THE COURSE
• COURSE OUTCOMES :
• CO1 : Describe data structures arrays, stacks
and queues
• CO2 : Interpret linked lists, trees and graphs
• CO3 : Demonstrate best-case, average-case
and the worst-case running times of
algorithms using asymptotic analysis for
various sorting and searching problems
• CO4 : Choose the standard design techniques
of algorithms and their applications
BASICS OF THE COURSE
• TEXT AND REFERENCE BOOKS
• 1. Yedidyah Langsam, Moshe J. Augenstein, Aaron
M.Tenenbaum, “Data Structures using C and C++ “ ,
Pearson Pub.
• 2. G.S. Baluja, “Principles of Data Structures using C
and C++”, Dhanpat Rai & Co.,4th Edition
• 3. Computer Algorithms : Horowitz, Sahani,
Rajsekharan , Galgotia Publications Pvt.Ltd
• 4. Fundamentals of Algorithms: Brassard, Bratley ,
Prentice Hall
BASICS OF THE COURSE
• WEB RESOURCES:
• 1. https://nptel.ac.in/courses/106102064
• 2. https://nptel.ac.in/courses/106106127
• 3.https://www.coursera.org/specializatio
ns/data-structures-algorithms
INTRODUCTION OF THE SUBJECT
• DATA –
• Processed information
• Interrelated information
INTRODUCTION OF THE SUBJECT
• STRUCTURE :
–The way that the parts of something
are put together or organized
–To arrange something in an organized
way
INTRODUCTION OF THE SUBJECT
•DATA STRUCTURE :
• Storage that is used to store and organize
data.
• A way of arranging data on a computer so
that it can be accessed and updated
efficiently.
INTRODUCTION OF THE SUBJECT
• ALGORITHM :
• The word Algorithm means ” A set of finite
rules or instructions to be followed in
calculations or other problem-solving
operations ”
INTRODUCTION OF THE SUBJECT
• Or
” A procedure for solving a mathematical
problem in a finite number of steps that
frequently involves recursive operations”.
INTRODUCTION OF THE SUBJECT
UNIT 1
INTRODUCTION TO DATA
STRUCTURES
UNIT 1
• SYLLABUS :
• Introduction to data structures, Concept of Data
type, Data object, Need of Data Structure, Types
of Data Structure, Linear data structures,
Introduction to Arrays, sorting algorithms with
efficiency, Stacks, static and dynamic
representation of stack, Stack Operations ,
Applications of stack, Queues, static & dynamic
representation of queues, Operations on queues,
Circular queue, priority queues
CONCEPT OF DATA TYPE
• What is Data Type? :
• The term “data type” in software programming
describes the kind of value a variable possesses
and the kinds of mathematical, relational, or
logical operations that can be performed on it
without leading to an error.
• Numerous programming languages, for instance,
utilize the data types string, integer, and floating
point to represent text, whole numbers, and
values with decimal points, respectively.
CONCEPT OF DATA TYPE
• An interpreter or compiler can determine how a
programmer plans to use a given set of data by
looking up its data type.
• The data comes in different forms. Examples
include:
• your name – a string of characters
• your age – usually an integer
• the amount of money in your pocket- usually
decimal type
• today’s date – written in date time format
CONCEPT OF DATA TYPE
CONCEPT OF DATA TYPE
• 1. Primitive Data Types:
• Primitives are predefined data types that are
independent of all other kinds and include basic
values of particular attributes, like text or
numeric values.
• They are the most fundamental type and are
used as the foundation for more complex data
types.
• Most computer languages probably employ some
variation of these simple data types.
CONCEPT OF DATA TYPE
• Common Primitive Data Types in
Programming:
Data Type Definition Examples
represent numeric data type for
Integer (int) 300, 0 , -300
numbers without fractions
Floating Point represent numeric data type for 34.67, 56.99, -
(float) numbers with fractions 78.09
• data_type
array_name[size1][size2]….[sizeN];
data_type: It defines the type of data
that can be held by an array. Here
data_type can be int, char, float. etc.
array_name: Name of the array
size1, size2,… ,sizeN: Sizes of the
dimensions
PICTORIAL REPRESENTATION OF A
MULTIDIMENSIONAL ARRAY
PICTORIAL REPRESENTATION OF A
MULTIDIMENSIONAL ARRAY
Operators Symbols
Parenthesis { }, ( ), [ ]
Exponential notation ^
Multiplication and *, /
Division
Addition and +, -
Subtraction
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• Associativity order
Operators Associativity
^ Right to Left
*, / Left to Right
+, - Left to Right
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• What is Prefix notation?
• It is also known as polish notation
• In prefix notation, an operator
comes before the operands. The
syntax of prefix notation is given
below:
• <operator> <operand> <operand>
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• For example, if the infix expression is
5+1, then the prefix expression
corresponding to this infix expression
is +51.
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• If the infix expression is:
• a*b+c
• Convert it into Prefix expression
• Step 1 : a * b + c
• Step 2 : *ab+c
• Step 3 : +*abc
CONVERSION OF INFIX TO PREFIX
EXPRESSION
• Consider another example:
•A+B*C
• Step 1: A + B * C
• Step 2 : A+*BC
• Step 3 : +A*BC
CONVERSION OF INFIX TO
POSTFIX EXPRESSION
CONVERSION OF INFIX TO POSTFIX
EXPRESSION
• Infix expression: The expression of the
form “a operator b” (a + b) i.e., when an
operator is in-between every pair of
operands.
• Postfix expression: The expression of the
form “a b operator” (ab+) i.e., When
every pair of operands is followed by an
operator.
CONVERSION OF INFIX TO POSTFIX
EXPRESSION
• Input: A + B * C + D
Output: ABC*+D+
EVALUATION OF POSTFIX
EXPRESSION USING STACK
Algorithm of Postfix Expression
Evaluation
• Create a stack that holds integer type
data to store the operands of the given
postfix expression. Let it be st.
• Iterate over the string from left to right
and do the following –
– If the current element is an operand, push it
into the stack.
– Otherwise, if the current element is an
operator (say /)do the following -
Algorithm of Postfix Expression
Evaluation
– Pop an element from st, let it be op1.
– Pop another element from st, let it be op2.
– Compute the result of op2 / op1, and push
it into the stack. Note the order i.e. op2 /
op1 should not be changed otherwise it will
affect the final result in some cases.
• At last, st will consist of a single
element i.e. the result after evaluating
the postfix expression.
Algorithm of Postfix Expression
Evaluation
• Let the the postfix expression be 10 22 +
8/6*5+
• Now, proceeding as per the algorithm –
• Create a stack (say st).
• Now since the first element is an
operand, so we will push it in the
stack .i.e. st.push(10). After which stack
looks like -
Algorithm of Postfix Expression
Evaluation
st
10
Algorithm of Postfix Expression
Evaluation
• Now we traverse further in the
postfix expression and found that
the next element is again an
operand. So, we will push it into
the stack, after which the stack
will look like -
Algorithm of Postfix Expression
Evaluation
st
22
10
Algorithm of Postfix Expression
Evaluation
• The next element of the expression is an
operator (+ operator) so we will do the
following –
– Pop an element (say op1) from the stack.
Here op1 = 22.
– Pop another element (say op2) from the
stack. Here op2 = 10.
– Now, we will compute op2 + op1 which
is 32, and push it into the stack. After this
step stack will look like -
Algorithm of Postfix Expression
Evaluation
st
32
Algorithm of Postfix Expression
Evaluation
• On traversing further in the
expression string, we found next
element is an operand. So we will
push it into the stack. Upon doing
this, the stack will look like -
Algorithm of Postfix Expression
Evaluation
st
8
32
Algorithm of Postfix Expression
Evaluation
• The next element is the / operator, so we
will do the following –
– Pop an element (say op1) from the stack.
Here op1 = 8.
– Pop another element (say op2) from the
stack. Here op2 = 32.
– Now, we will compute op2 / op1 which is 4,
and push it into the stack. After this step
stack will look like -
Algorithm of Postfix Expression
Evaluation
st
4
Algorithm of Postfix Expression
Evaluation
• The next element is an
operand, hence pushing it in
the stack. After this step stack
will look like -
Algorithm of Postfix Expression
Evaluation
st
6
4
Algorithm of Postfix Expression
Evaluation
• The next element is the * operator,
hence we need to perform the following
steps -
– Pop an element (say op1) from the stack.
Here op1 = 6.
– Pop another element (say op2) from the
stack. Here op2 = 4.
– Now, we will compute op2 * op1 which
is 24, and push it into the stack. After this
step stack will look like -
Algorithm of Postfix Expression
Evaluation
st
24
Algorithm of Postfix Expression
Evaluation
• The next operator is an operand,
hence pushing it into the stack.
Upon doing which stack will look
like -
Algorithm of Postfix Expression
Evaluation
st
5
24
Algorithm of Postfix Expression
Evaluation
• The last element is the + operator. Hence
it is required to do the following steps -
– Pop an element (say op1) from the stack.
Here op1 = 5.
– Pop another element (say op2) from the
stack. Here op2 = 24.
– Now, we will compute op2 + op1 which
is 29, and push it into the stack. After this
step stack will look like -
Algorithm of Postfix Expression
Evaluation
st
29
Algorithm of Postfix Expression
Evaluation
• Now, we have traversed the
given postfix expression, and
hence as per the algorithm the
only element remaining in the
stack i.e. 29 is the result we
get on evaluating the postfix
expression.
UNIT - II
LINKED LIST
IMPLEMENTATION OF LIST
• A linked list is a fundamental data structure in
computer science.
• It mainly allows
efficient insertion and deletion operations
compared to arrays.
• Like arrays, it is also used to implement other
data structures like stack, queue and deque.
IMPLEMENTATION OF LIST
• What is a Linked List?
• A linked list is a linear data structure that consists
of a series of nodes connected by pointers (in C
or C++) or references (in Java, Python and
JavaScript).
• Each node contains data and
a pointer/reference to the next node in the list.
• Unlike arrays, linked lists allow for
efficient insertion or removal of elements from
any position in the list, as the nodes are not
stored contiguously in memory.
IMPLEMENTATION OF LIST
TYPES OF LINKED LIST
TYPES OF LINKED LIST
• 1. SINGLY LINKED LIST
• It is the simplest type of linked list in which
every node contains some data and a pointer
to the next node of the same data type.
TYPES OF LINKED LIST
• The node contains a pointer to the next
node means that the node stores the
address of the next node in the
sequence.
• A single linked list allows the traversal of
data only in one way.
• Time Complexity: O(N)
Auxiliary Space: O(N)
TYPES OF LINKED LIST
• 2. DOUBLY LINKED LIST
• A doubly linked list or a two-way linked list is a
more complex type of linked list that contains
a pointer to the next as well as the previous
node in sequence.
• Therefore, it contains three parts of data, a
pointer to the next node, and a pointer to the
previous node. This would enable us to
traverse the list in the backward direction as
well. Below is the image for the same:
TYPES OF LINKED LIST
TYPES OF LINKED LIST
• TIME COMPLEXITY:
• The time complexity of the push() function is
O(1)
• The time complexity of the printList() function
is O(n) iswhere n is the number of nodes in
the doubly linked list.
• Space Complexity:
The space complexity of the program is O(n)
as it uses a doubly linked list to store the data,
which requires n nodes
TYPES OF LINKED LIST
• 3. CIRCULAR LINKED LIST
• A circular linked list is that in which the last node
contains the pointer to the first node of the list.
• While traversing a circular linked list, we can
begin at any node and traverse the list in any
direction forward and backward until we reach
the same node we started. Thus, a circular linked
list has no beginning and no end. Below is the
image for the same:
TYPES OF LINKED LIST
TYPES OF LINKED LIST
• Time Complexity:
• Insertion at the beginning of the circular linked list takes O(1) time
complexity.
Traversing and printing all nodes in the circular linked list takes O(n)
time complexity where n is the number of nodes in the linked list.
Therefore, the overall time complexity of the program is O(n).
• Auxiliary Space:
• The space required by the program depends on the number of
nodes in the circular linked list.
In the worst-case scenario, when there are n nodes, the space
complexity of the program will be O(n) as n new nodes will be
created to store the data.
Additionally, some extra space is required for the temporary
variables and the function calls.
Therefore, the auxiliary space complexity of the program is O(n).
TYPES OF LINKED LIST
• 4. DOUBLY CIRCULAR LINKED LIST
• A Doubly Circular linked list or a circular two-way
linked list is a more complex type of linked list
that contains a pointer to the next as well as the
previous node in the sequence.
• The difference between the doubly linked and
circular doubly list is the same as that between a
singly linked list and a circular linked list.
• The circular doubly linked list does not contain
null in the previous field of the first node. Below
is the image for the same:
TYPES OF LINKED LIST
TYPES OF LINKED LIST
• Time Complexity:
• Insertion at the beginning of a doubly circular linked list takes O(1)
time complexity.
Traversing the entire doubly circular linked list takes O(n) time
complexity, where n is the number of nodes in the linked list.
Therefore, the overall time complexity of the program is O(n).
• Auxiliary space:
• The program uses a constant amount of auxiliary space, i.e., O(1),
to create and traverse the doubly circular linked list.
The space required to store the linked list grows linearly with the
number of nodes in the linked list.
Therefore, the overall auxiliary space complexity of the program is
O(1).
OPERATIONS ON LIST
OPERATIONS ON LIST
• These are the following operations on Linked
List :
• 1. Insertion in Linked List
• 2. Search an element in a Linked List
• 3. Find Length of a Linked List
• 4. Reverse a Linked List
• 5. Deletion in Linked List
OPERATIONS ON LIST
• 1. INSERTION IN LINKED LIST :
• Given a Linked List, the task is to insert a new
node in this given Linked List at the following
positions:
a. At the front of the linked list
b. After a given node.
c. At a specific position.
d. At the end of the linked list.
OPERATIONS ON LIST
• A. Insert a Node at the Front/Beginning of
Linked List
• To insert a new node at the front, we create
a new node and point its next reference to
the current head of the linked list. Then, we
update the head to be this new node. This
operation is efficient because it only requires
adjusting a few pointers.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Algorithm:
• Make the first node of Linked List linked to the
new node
• Remove the head from the original first node
of Linked List
• Make the new node as the Head of the Linked
List.
OPERATIONS ON LIST
• B. Insert a Node after a Given Node in Linked
List
• If we want to insert a new node after a
specific node, we first locate that node. Once
we find it, we set the new node’s next
reference to point to the node that follows the
given node. Then, we update the given node’s
next to point to the new node. This requires
traversing the list to find the specified node.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Algorithm:
• Initialize a pointer curr to traverse the list starting from
head.
• Loop through the list to find the node with data equal
to key.
– If not found then return from function.
• Create a new node, say new_node initialized with the
given data.
• Make the next pointer of new_node as next of given
node.
• Update the next pointer of given node point to
the new_node.
OPERATIONS ON LIST
• C. Insert a Node At a Specific Position in
Linked List
• To insert a new node at a specific position, we
need to traverse the list to position – 1. If the
position is valid, we adjust the pointers
similarly such that the next pointer of the new
node points to the next of current
nod and next pointer of current
node points to the new node.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Algorithm:
• Traverse the Linked list upto position-1 nodes.
• Once all the position-1 nodes are traversed,
allocate memory and the given data to the
new node.
• Point the next pointer of the new node to the
next of current node.
• Point the next pointer of current node to the
new node.
OPERATIONS ON LIST
• D. Insert a Node at the End of Linked List
• Inserting at the end involves traversing the
entire list until we reach the last node. We
then set the last node’s next reference to
point to the new node, making the new
node the last element in the list.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Algorithm:
• Go to the last node of the Linked List
• Change the next pointer of last node from
NULL to the new node
• Make the next pointer of new node as NULL to
show the end of Linked List
OPERATIONS ON LIST
• 2. Search an element in a Linked List
• Given a linked list and a key, the task is to check
if key is present in the linked list or not.
• Examples:
• Input: 14 -> 21 -> 11 -> 30 -> 10, key = 14
Output: Yes
Explanation: 14 is present in the linked list.
• Input: 6 -> 21 -> 17 -> 30 -> 10 -> 8, key = 13
Output: No
Explanation: No node in the linked list has value
= 13.
OPERATIONS ON LIST
• The idea is to traverse all the nodes of the linked
list, starting from the head. While traversing, if
we find a node whose value is equal to key then
print “Yes”, otherwise print “No”.
• Algorithm :
• Initialize a node pointer, curr = head.
• Do following while current is not NULL
– If the current value (i.e., curr->key) is equal to the key
being searched return true.
– Otherwise, move to the next node (curr = curr->next).
• If the key is not found, return false
OPERATIONS ON LIST
• 3. Find Length of a Linked List
• Given a Singly Linked List, the task is to find
the Length of the Linked List.
• Examples:
• Input: LinkedList = 1->3->1->2->1
Output: 5
• Input: LinkedList = 2->4->1->9->5->3->6
Output: 7
OPERATIONS ON LIST
• The idea is similar to traversal of Linked List with
an additional variable to count the number of
nodes in the Linked List.
• ALGORITHM:
• Initialize count as 0.
• Initialize a node pointer, curr = head.
• Do following while curr is not NULL
– curr = curr -> next
– Increment count by 1.
• Return count.
OPERATIONS ON LIST
• 4. Reverse a Linked List
• Input: Linked List = 1 -> 2 -> 3 -> 4 -> NULL
Output: Reversed Linked List = 4 -> 3 -> 2 -> 1 ->
NULL
• Input: Linked List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output: Reversed Linked List = 5 -> 4 -> 3 -> 2 -> 1
-> NULL
• Input: Linked List = NULL
Output: Reversed Linked List = NULL
• Input: Linked List = 1->NULL
Output: Reversed Linked List = 1->NULL
OPERATIONS ON LIST
• The idea is to reverse the links of all nodes
using three pointers:
• prev: pointer to keep track of the previous node
• curr: pointer to keep track of the current node
• next: pointer to keep track of the next node
• Starting from the first node, initialize curr with
the head of linked list and next with the next node
of curr. Update the next pointer of curr with prev.
Finally, move the three pointer by
updating prev with curr and curr with next.
OPERATIONS ON LIST
• Follow the steps below to solve the problem:
• Initialize three pointers prev as
NULL, curr as head, and next as NULL.
• Iterate through the linked list. In a loop, do the
following:
– Store the next node, next = curr -> next
– Update the next pointer of curr to prev, curr -> next =
prev
– Update prev as curr and curr as next, prev =
curr and curr = next
OPERATIONS ON LIST
• 5. Deletion in Linked List
• Deleting a node in a Linked List is an important
operation and can be done in three main
ways: removing the first node, removing a
node in the middle, or removing the last node.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Types of Deletion in Linked List
• 1. Deletion at the Beginning of Linked List
• 2. Deletion at Middle of the Linked List
• 3. Deletion at the End of Linked List
OPERATIONS ON LIST
• 1. Deletion at the Beginning of Linked List
• Deletion at the Beginning operation involves
removing the first node of the linked list.
• To perform the deletion at the beginning of
Linked List, we need to change
the head pointer to point to the second node.
If the list is empty, there’s nothing to delete.
OPERATIONS ON LIST
• 2. Deletion at Middle of the Linked List
• Deletion at middle refers to deleting a node
that is neither the first nor the last node in the
linked list.
• To delete a node in the middle, we must first
traverse the list to find the node just before
the one we want to delete. Then, adjust the
pointers to bypass the node being deleted.
OPERATIONS ON LIST
• 3. Deletion at the End of Linked List
• Deletion at the end operation involves
removing the last node of the linked list.
• To perform the deletion at the end of Linked
List, we need to traverse the list to find
the second last node, then set its next pointer
to null. If the list is empty then there is no
node to delete or has only one node then
point head to null.
OPERATIONS ON LIST
• Delete a Linked List node at a given position
• Given a singly linked list and a position (1-
based indexing), the task is to delete a linked
list node at the given position.
• Example:
• Input: position = 2, Linked List = 8->2->3->1->7
Output: Linked List = 8->3->1->7
• Input: position = 1, Linked List = 8->2->3->1->7
Output: Linked List = 2->3->1->7
OPERATIONS ON LIST
• Approach:
• To delete a linked list node at a given position, we have
to starts by checking edge cases like, if the list is empty
(head == NULL) or not, we have to do nothing. After
then, check if the position is the first node, then
updates the head to point its next node, this will
effectively remove the first node. For other positions,
traverses the list to find the node (previous node) just
before the target position, then changes the next
of previous node to target’s next node. If the target
position is greater than the length of given list, it
indicates that the position is not present.
OPERATIONS ON LIST
OPERATIONS ON LIST
• Step-by-step approach:
• If list is empty (head == NULL), returns the head.
• If the position to delete is 1 (the head node):
– Update head = temp->next
• Traverse the list until reaching the desired position:
– Initialize prev to keep track of the previous node.
– Move temp through the list until the position is reached.
• Check for Valid Position:
– If temp becomes NULL, it means the position exceeds the
number of nodes in the list. Print a message and return
the head.
• If the node to delete is found:
– Set prev->next to temp->next, effectively skipping over
the node to be deleted.
APPLICATIONS OF
LINKED LIST
APPLICATIONS OF LINKED LIST
• Applications of Linked Lists:
• Linked Lists can be used to implement stacks,
queue, deque, sparse matrices and adjacency
list representation of graphs.
• Dynamic memory allocation in operating
systems and compilers (linked list of free
blocks).
APPLICATIONS OF LINKED LIST
• Manipulation of polynomials
• Arithmetic operations on long integers.
• In operating systems, they can be used in
Memory management, process scheduling (for
example circular linked list for round robin
scheduling) and file system.
APPLICATIONS OF LINKED LIST
• Algorithms that need to frequently insert or
delete items from large collections of data.
• LRU cache, which uses a doubly linked list to
keep track of the most recently used items in a
cache.
APPLICATIONS OF LINKED LIST
• Applications of Linked Lists in real world:
• The list of songs in the music player are linked
to the previous and next songs.
• In a web browser, previous and next web page
URLs can be linked through the previous and
next buttons (Doubly Linked List)
• In image viewer, the previous and next images
can be linked with the help of the previous
and next buttons (Doubly Linked List)
APPLICATIONS OF LINKED LIST
• Circular Linked Lists can be used to implement
things in round manner where we go to every
element one by one.
• Linked List are preferred over arrays for
implementations of Queue and Deque data
structures because of fast deletions (or
insertions) from the front of the linked lists.
TREES
TREES
• Tree data structure is a specialized data
structure to store data in hierarchical manner.
• It is used to organize and store data in the
computer to be used more effectively.
• It consists of a central node, structural nodes,
and sub-nodes, which are connected via
edges.
• We can also say that tree data structure has
roots, branches, and leaves connected.
TREES
• Tree data structure is a hierarchical structure that
is used to represent and organize data in a way
that is easy to navigate and search.
• It is a collection of nodes that are connected by
edges and has a hierarchical relationship between
the nodes.
• The topmost node of the tree is called the root,
and the nodes below it are called the child nodes.
• Each node can have multiple child nodes, and
these child nodes can also have their own child
nodes, forming a recursive structure.
TREES
• Why Tree is considered a non-linear data
structure?
• The data in a tree are not stored in a
sequential manner i.e., they are not stored
linearly.
• Instead, they are arranged on multiple levels
or we can say it is a hierarchical structure.
• For this reason, the tree is considered to be
a non-linear data structure.
TREES
BASIC
TERMINOLOGIES
BASIC TERMINOLOGIES
• Parent Node: The node which is a predecessor of
a node is called the parent node of that
node. {B} is the parent node of {D, E}.
• Child Node: The node which is the immediate
successor of a node is called the child node of
that node. Examples: {D, E} are the child nodes
of {B}.
• Root Node: The topmost node of a tree or the
node which does not have any parent node is
called the root node. {A} is the root node of the
tree. A non-empty tree must contain exactly one
root node and exactly one path from the root to
all other nodes of the tree.
TREES
• Leaf Node or External Node: The nodes which do
not have any child nodes are called leaf nodes. {I,
J, K, F, G, H} are the leaf nodes of the tree.
• Ancestor of a Node: Any predecessor nodes on
the path of the root to that node are called
Ancestors of that node. {A,B} are the ancestor
nodes of the node {E}
• Descendant: A node x is a descendant of another
node y if and only if y is an ancestor of x.
TREES
• Sibling: Children of the same parent node are
called siblings. {D,E} are called siblings.
• Level of a node: The count of edges on the path
from the root node to that node. The root node
has level 0.
• Internal node: A node with at least one child is
called Internal Node.
• Neighbour of a Node: Parent or child nodes of
that node are called neighbours of that node.
• Subtree: Any node of the tree along with its
descendant.
TREES
TREES
• Tree data structure can be classified into three
types based upon the number of children
each node of the tree can have. The types are:
• BINARY TREE: In a binary tree, each node can
have a maximum of two children linked to it.
Some common types of binary trees include
full binary trees, complete binary trees,
balanced binary trees, and degenerate or
pathological binary trees.
TREES
• TERNARY TREE: A Ternary Tree is a tree data
structure in which each node has at most three
child nodes, usually distinguished as “left”, “mid”
and “right”.
• N-ARY TREE OR GENERIC TREE: Generic trees are
a collection of nodes where each node is a data
structure that consists of records and a list of
references to its children(duplicate references are
not allowed). Unlike the linked list, each node
stores the address of multiple nodes.
OPERATIONS ON BINARY
TREES
OPERATIONS ON BINARY TREES
• What is Binary Tree?
• Binary tree is a tree data structure(non-
linear) in which each node can have at most
two children which are referred to as the left
child and the right child.
• The topmost node in a binary tree is called
the root, and the bottom-most nodes are
called leaves. A binary tree can be visualized
as a hierarchical structure with the root at the
top and the leaves at the bottom.
• Basic Operations on Binary Tree:
1. Tree Traversals (Inorder, Preorder and Postorder)
2. Level Order Tree Traversal
3. Find the Maximum Depth or Height of given
Binary Tree
4. Insertion in a Binary Tree
5. Deletion in a Binary Tree
6. Enumeration of Binary Trees
• TREE TRAVERSALS (INORDER, PREORDER AND
POSTORDER) :
• Tree Traversal Meaning:
• Tree Traversal refers to the process of visiting or accessing
each node of the tree exactly once in a certain order.
• Tree traversal algorithms help us to visit and process all the
nodes of the tree.
• Since tree is not a linear data structure, there are multiple
nodes which we can visit after visiting a certain node.
• There are multiple tree traversal techniques which decide
the order in which the nodes of the tree are to be visited.
• Tree Traversal Techniques:
• A Tree Data Structure can be traversed in
following ways:
• Depth First Search or DFS
– Inorder Traversal
– Preorder Traversal
– Postorder Traversal
• Level Order Traversal or Breadth First Search
or BFS
• INORDER TRAVERSAL:
• Inorder traversal visits the node in the order: Left
-> Root -> Right
• Algorithm for Inorder Traversal:
• Inorder(tree)
• Traverse the left subtree, i.e., call Inorder(left-
>subtree)
• Visit the root.
• Traverse the right subtree, i.e., call Inorder(right-
>subtree)
• PREORDER TRAVERSAL:
• Preorder traversal visits the node in the
order: Root -> Left -> Right
• Algorithm for Preorder Traversal:
• Preorder(tree)
• Visit the root.
• Traverse the left subtree, i.e., call Preorder(left-
>subtree)
• Traverse the right subtree, i.e., call
Preorder(right->subtree)
• POSTORDER TRAVERSAL:
• Postorder traversal visits the node in the
order: Left -> Right -> Root
• Algorithm for Postorder Traversal:
• Algorithm Postorder(tree)
• Traverse the left subtree, i.e., call Postorder(left-
>subtree)
• Traverse the right subtree, i.e., call
Postorder(right->subtree)
• Visit the root
2. LEVEL ORDER TRAVERSAL :
• Level Order Traversal visits all nodes present
in the same level completely before visiting
the next level.
• Algorithm for Level Order Traversal:
• LevelOrder(tree)
• Create an empty queue Q
• Enqueue the root node of the tree to Q
• Loop while Q is not empty
– Dequeue a node from Q and visit it
– Enqueue the left child of the dequeued node if it
exists
– Enqueue the right child of the dequeued node if it
exists
3. FIND THE MAXIMUM DEPTH OR HEIGHT OF
GIVEN BINARY TREE
• Given a binary tree, the task is to find the
maxim depth or height of the tree.
• The height of the tree is the number of
vertices in the tree from the root to the
deepest node.
• Algorithm (Using Recursion):
• Recursively calculate the height of the left and
the right subtrees of a node and assign height
to the node as max of the heights of two
children plus 1. See below the pseudo code
and program for details.
• If the tree is empty then return 0
• Otherwise, do the following -
– Get the max depth of the left subtree
recursively i.e. call maxDepth( tree->left-subtree)
– Get the max depth of the right subtree
recursively i.e. call maxDepth( tree->right-
subtree)
– Get the max of max depths
of left and right subtrees and add 1 to it for the
current node.
• max_depth = max(max_depth of left subtree, max
depth of right subtree) + 1
• Return max_depth.
• Illustration :
APPLICATIONS OF TREES
APPLICATIONS OF TREES
• File System: This allows for efficient
navigation and organization of files.
• Data Compression:Huffman coding is a
popular technique for data compression that
involves constructing a binary tree where the
leaves represent characters and their
frequency of occurrence. The resulting tree is
used to encode the data in a way that
minimizes the amount of storage required.
APPLICATIONS OF TREES
• Compiler Design: In compiler design, a syntax
tree is used to represent the structure of a
program.
• Database Indexing: B-trees and other tree
structures are used in database indexing to
efficiently search for and retrieve data.