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

DSA Module - 3

data structures module 3 notes

Uploaded by

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

DSA Module - 3

data structures module 3 notes

Uploaded by

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

Data Structures and Applications (BCS304) Module - 3

SPARSE MATRIX REPRESENTATION

A linked list representation for sparse matrices.

In data representation, each column of a sparse matrix is represented as a circularly linked listwith a
header node. A similar representation is used for each row of a sparse matrix.
Each node has a tag field, which is used to distinguish between header nodes and entry nodes.

Header Node:
 Each header node has three fields: down, right, and next as shown in figure (a).
 The down field is used to link into a column list and the right field to link into a row list.
 The next field links the header nodes together.
 The header node for row i is also the header node for column i, and the total number of
header nodes is max {number of rows, number of columns}.

Element node:
 Each element node has five fields in addition in addition to the tag field: row, col, down, right,
value as shown in figure (b).
 The down field is used to link to the next nonzero term in the same column and the right field
to link to the next nonzero term in the same row. Thus, if aij ≠ 0, there is a node with tag
field = entry, value = aij, row = i, and col = j as shown in figure (c).
 We link this node into the circular linked lists for row i and column j. Hence, it is
simultaneously linked into two different lists.

Consider the sparse matrix, as shown in below figure (2).

Figure (3) shows the linked representation of this matrix. Although we have not shown thevalue of

Dept. of Data Science and AIML, A.I.T, CKM Page 1


Data Structures and Applications (BCS304) Module - 3

the tag fields, we can easily determine these values from the node structure.
For each nonzero term of a, have one entry node that is in exactly one row list and one column list.
The header nodes are marked HO-H3. As the figure shows, we use the right field of the header node
list header to link into the list of header nodes.

To represent a numRows x numCols matrix with numTerms nonzero terms, then we need max
{numRows, numCols} + numTerms + 1 nodes. While each node may require several words of memory,
the total storage will be less than numRows x numCols when numTerms is sufficiently small.

There are two different types of nodes in representation, so unions are used to create theappropriate
data structure. The C declarations are as follows:

Dept. of Data Science and AIML, A.I.T, CKM Page 2


Data Structures and Applications (BCS304) Module - 3

ADDITIONAL LIST OPERATIONS

 Operations for Chains


 Operations for circular Linked List

Dept. of Data Science and AIML, A.I.T, CKM Page 3


Data Structures and Applications (BCS304) Module - 3

CIRCULAR LINKED LISTS

In a circular linked list, the last node contains a pointer to the first node of the list. We can have a circular
singly linked list as well as a circular doubly linked list. While traversing a circular linked list, we can
begin at any node and traverse the list in any direction, forward or backward, until we reach the same

Dept. of Data Science and AIML, A.I.T, CKM Page 4


Data Structures and Applications (BCS304) Module - 3

node where we started. Thus, a circular linked list has no beginning and no ending. Figure 6.26 shows a
circular linked list.

Inserting a Node at the Beginning of a Circular Linked List

Consider the linked list shown in Fig. 6.29. Suppose we want to add a new node with data 9 as the first
node of the list. Then the following changes will be done in the linked list.

Figure 6.30 shows the algorithm to insert a new node at the beginning of a linked list. In Step 1, we first
check whether memory is available for the new node. If the free memory has exhausted, then an
OVERFLOW message is printed. Otherwise, if free memory cell is available, then we allocate space for

Dept. of Data Science and AIML, A.I.T, CKM Page 5


Data Structures and Applications (BCS304) Module - 3

the new node. Set its DATA part with the given VAL and the NEXT part is initialized with the address of
the first node of the list, which is stored in START.

Now, since the new node is added as the first node of the list, it will now be known as the START node,
that is, the START pointer variable will now hold the address of the NEW_NODE.
While inserting a node in a circular linked list, we have to use a while loop to traverse to the last node of
the list. Because the last node contains a pointer to START, its NEXT field is updated so that after
insertion it points to the new node which will be now known as START.

Function to insert a node at the beginning of circular linked list

DOUBLY LINKED LIST

1. The difficulties with single linked lists is that, it is possible to traversal only in one direction,
i.e., direction of the links.
2. The only way to find the node that precedes p is to start at the beginning of the list. The same
problem arises when one wishes to delete an arbitrary node from a singly linked list. Hence
the solution is to use doubly linked list

A doubly linked list or a two-way linked list is a more complex type of linked list which contains a
pointer to the next as well as the previous node in the sequence. Therefore, it consists of three parts—
data, a pointer to the next node, and a pointer to the previous node as shown in Fig. 6.37.

In C, the structure of a doubly linked list can be given as,

struct node {

Dept. of Data Science and AIML, A.I.T, CKM Page 6


Data Structures and Applications (BCS304) Module - 3

struct node *prev;


int data;
struct node *next;
};

The PREV field of the first node and the NEXT field of the last node will contain NULL. The PREV field
is used to store the address of the preceding node, which enables us to traverse the list in the backward
direction.

Inserting a new node in a doubly Linked List

In this section, we will discuss how a new node is added into an already existing doubly linked list. We
will take four cases and then see how insertion is done in each case.

Case 1: The new node is inserted at the beginning.


Case 2: The new node is inserted at the end.
Case 3: The new node is inserted after a given node.
Case 4: The new node is inserted before a given node.

Inserting a Node at the Beginning of a Doubly Linked List

Consider the doubly linked list shown in Fig. 6.39. Suppose we want to add a new node with data 9 as the
first node of the list. Then the following changes will be done in the linked list.

Figure 6.40 shows the algorithm to insert a new node at the beginning of a doubly linked list. In Step 1,
we first check whether memory is available for the new node. If the free memory has exhausted, then an

Dept. of Data Science and AIML, A.I.T, CKM Page 7


Data Structures and Applications (BCS304) Module - 3

OVERFLOW message is printed. Otherwise, if free memory cell is available, then we allocate space for
the new node. Set its DATA part with the given VAL and the NEXT part is initialized with the address of
the first node of the list, which is stored in START.

Now, since the new node is added as the first node of the list, it will now be known as the START node,
that is, the START pointer variable will now hold the address of NEW_NODE.

Function to insert a node at the beginning of the linked list

Inserting a Node at the End end of a Doubly Linked List

Consider the doubly linked list shown in Fig. 6.41. Suppose


we want to add a new node with data 9 as the last node of the list. Then the following changes will be
done in the linked list.

Dept. of Data Science and AIML, A.I.T, CKM Page 8


Data Structures and Applications (BCS304) Module - 3

Figure 6.42 shows the algorithm to insert a new node at the end of a doubly linked list. In Step 6, we take
a pointer variable PTR and initialize it with START. In the while loop, we traverse through the linked list
to reach the last node. Once we reach the last node, in Step 9, we change the NEXT pointer of the last
node to store the address of the new node.

Remember that the NEXT field of the new node contains NULL which signifies the end of the linked list.
The PREV field of the NEW_NODE will be set so that it points to the node pointed by PTR (now the
second last node of the list).

Deleting the First Node from a Doubly Linked List

Consider the doubly linked list shown in Fig. 6.47. When we want to delete a node from the beginning of
the list, then the following changes will be done in the linked list.

Dept. of Data Science and AIML, A.I.T, CKM Page 9


Data Structures and Applications (BCS304) Module - 3

Figure 6.48 shows the algorithm to delete the first node of a doubly linked list. In Step 1 of the algorithm,
we check if the linked list exists or not. If START = NULL, then it signifies that there are no nodes in the
list and the control is transferred to the last statement of the algorithm.

However, if there are nodes in the linked list, then we use a temporary pointer variable PTR that is set to
point to the first node of the list. For this, we initialize PTR with START that stores the address of the
first node of the list. In Step 3, START is made to point to the next node in sequence and finally the
memory
occupied by PTR (initially the first node of the list) is freed and returned to the free pool.

Function to delete the first node in a Doubly Linked List

TREES

DEFINITION
A tree is a finite set of one or more nodes such that
 There is a specially designated node called root.
 The remaining nodes are partitioned into n >= 0 disjoint set T1,…,Tn, where each of these sets
is a tree. T1,…,Tn are called the subtrees of the root.

Every node in the tree is the root of some subtree

TERMINOLOGY

 Node: The item of information plus the branches to other nodes


 Degree: The number of subtrees of a node
 Degree of a tree: The maximum of the degree of the nodes in the tree.
 Terminal nodes (or leaf): nodes that have degree zero or node with no successor
 Nonterminal nodes: nodes that don’t belong to terminal nodes.

Dept. of Data Science and AIML, A.I.T, CKM Page 10


Data Structures and Applications (BCS304) Module - 3

 Parent and Children: Suppose N is a node in T with left successor S1 and right successor S2,
then N is called the Parent (or father) of S1 and S2. Here, S1 is called left child (or Son) and S2
is called right child (or Son) of N.
 Siblings: Children of the same parent are said to be siblings.
 Edge: A line drawn from node N of a T to a successor is called an edge
 Path: A sequence of consecutive edges from node N to a node M is called a path.
 Ancestors of a node: All the nodes along the path from the root to that node.
 The level of a node: defined by letting the root be at level zero. If a node is at level l, then it
children are at level l+1.
 Height (or depth): The maximum level of any node in the tree

A is the root node


B is the parent of E and F
C and D are the sibling of B E and F are the children of B
K, L, F, G, M, I, J are external nodes, or leaves
A, B, C, D, E, H are internal nodes
The level of E is 3
The height (depth) of the tree is 4
The degree of node B is 2
The degree of the tree is 3
The ancestors of node M is A, D, H
The descendants of node D is H, I, J, M

Dept. of Data Science and AIML, A.I.T, CKM Page 11


Data Structures and Applications (BCS304) Module - 3

Representation of Trees

There are several ways to represent a given tree such as:

Figure (A)

1. List Representation
2. Left Child- Right Sibling Representation
3. Representation as a Degree-Two tree

List Representation:

The tree can be represented as a List. The tree of figure (A) could be written as the list.
(A (B (E (K, L), F), C (G), D (H (M), I, J) ) )

 The information in the root node comes first.


 The root node is followed by a list of the subtrees of that node.

Tree node is represented by a memory node that has fields for the data and pointers to the treenode's
children

Since the degree of each tree node may be different, so memory nodes with a varying number of

Dept. of Data Science and AIML, A.I.T, CKM Page 12


Data Structures and Applications (BCS304) Module - 3

pointer fields are used.

For a tree of degree k, the node structure can be represented as below figure. Each child field is
used to point to a subtree.

Left Child-Right Sibling Representation

The below figure show the node structure used in the left child-right sibling representation

Representation as a Degree-Two Tree

To obtain the degree-two tree representation of a tree, simply rotate the right-sibling pointers in a
left child-right sibling tree clockwise by 45 degrees. This gives us the degree-two tree displayed in
Figure (E).

Figure (E): degree-two representation

In the degree-two representation, a node has two children as the left and right children.

To convert the tree of Figure (A) into this representation:


1. First note that every node has at most one leftmost child
2. At most one closest right sibling.

Dept. of Data Science and AIML, A.I.T, CKM Page 13


Data Structures and Applications (BCS304) Module - 3

BINARY TREES
Definition: A binary tree T is defined as a finite set of nodes such that,
 T is empty or
 T consists of a root and two disjoint binary trees called the left subtree and the right
subtree.

Figure: Binary Tree

Different kinds of Binary Tree

1. Skewed Tree
A skewed tree is a tree, skewed to the left or skews to the right.
or
It is a tree consisting of only left subtree or only right subtree.
 A tree with only left subtrees is called Left Skewed Binary Tree.
 A tree with only right subtrees is called Right Skewed Binary Tree.

2. Complete Binary Tree


A binary tree T is said to complete if all its levels, except possibly the last level, have the maximum
number node 2i, i ≥ 0 and if all the nodes at the last level appears as far left aspossible.

Figure (a): Skewed binary tree Figure (b): Complete binary tree

Dept. of Data Science and AIML, A.I.T, CKM Page 14


Data Structures and Applications (BCS304) Module - 3

3. Full Binary Tree


A full binary tree of depth ‘k’ is a binary tree of depth k having 2k – 1 nodes, k ≥ 1.

Figure: Full binary tree of level 4 with sequential node number

4. Extended Binary Trees or 2-trees


An extended binary tree is a transformation of any binary tree into a complete binary tree. This
transformation consists of replacing every null subtree of the original tree with “special nodes.”
The nodes from the original tree are then internal nodes, while the special nodes are external
nodes.
For instance, consider the following binary tree.

The following tree is its extended binary tree. The circles represent internal nodes, and square
represent external nodes.
Every internal node in the extended tree has exactly two children, and every external node is a
leaf. The result is a complete binary tree.

Dept. of Data Science and AIML, A.I.T, CKM Page 15


Data Structures and Applications (BCS304) Module - 3

PROPERTIES OF BINARY TREES

Lemma 1: [Maximum number of nodes]:


(1) The maximum number of nodes on level i of a binary tree is 2 i-1, i ≥ 1.
(2) The maximum number of nodes in a binary tree of depth k is 2k -1, k ≥ 1.

Proof:
(1) The proof is by induction on i.
Induction Base: The root is the only node on level i = 1. Hence, the maximum number of nodes on
level i =1 is 2i-1 = 20 = 1.
Induction Hypothesis: Let i be an arbitrary positive integer greater than 1. Assume that the maximum
number of nodes on level i -1is 2i-2
Induction Step: The maximum number of nodes on level i -1 is 2i-2 by the induction hypothesis.
Since each node in a binary tree has a maximum degree of 2, the maximum number of nodes on
level i is two times the maximum number of nodes on level i-1, or 2i-1

(2) The maximum number of nodes in a binary tree of depth k is


k k
k
∑ (maximum number of nodes on level i) =∑ 2i-1 = 2k-1
i=0 i=0

Lemma 2: [Relation between number of leaf nodes and degree-2 nodes]:


For any nonempty binary tree, T, if n0 is the number of leaf nodes and n2 the number of nodes of
degree 2, then n0 = n2 + 1.

Proof: Let n1 be the number of nodes of degree one and n the total number of nodes.
Since all nodes in T are at most of degree two, we have
n = n0 + n1+ n2 (1)
Count the number of branches in a binary tree. If B is the number of branches, then n
=B + 1.
All branches stem from a node of degree one or two. Thus,
B = n 1+ 2n2.
Hence, we obtain
n = B + 1= n 1+ 2n2 + 1 (2)

Subtracting Eq. (2) from Eq. (1) and rearranging terms, we get

n0 = n2 +1

Dept. of Data Science and AIML, A.I.T, CKM Page 16


Data Structures and Applications (BCS304) Module - 3

Representation of Binary Trees in the Memory

In the computer’s memory, a binary tree can be maintained either by using a linked representation or by
using a sequential representation.

Linked representation of binary trees In the linked representation of a binary tree, every node will have
three parts: the data element, a pointer to the left node, and a pointer to the right node. So in C, the binary
tree is built with a node type given below.

struct node {
struct node *left;
int data ;
struct node *right;
};

Every binary tree has a pointer ROOT, which points to the root element (topmost element) of the tree. If
ROOT = NULL, then the tree is empty. Consider the binary tree given in Fig. 9.3. The schematic diagram
of the linked representation of the binary tree is shown in Fig. 9.9.

Dept. of Data Science and AIML, A.I.T, CKM Page 17


Data Structures and Applications (BCS304) Module - 3

Linked representation of the binary tree

Sequential representation of binary trees

Sequential representation of trees is done using single or one-dimensional arrays. Though it is the
simplest technique for memory representation, it is inefficient as it requires a lot of memory space. A
sequential binary tree follows the following rules:

Dept. of Data Science and AIML, A.I.T, CKM Page 18


Data Structures and Applications (BCS304) Module - 3

BINARY TREE TRAVERSALS

Visiting each node in a tree exactly once is called tree traversal

The different methods of traversing a binary tree are:


1. Preorder
2. Inorder
3. Postorder
4. Iterative inorder Traversal
5. Level-Order traversal

Let ptr is the pointer which contains the location of the node N currently being scanned. L(N) denotes the
leftchild of node N and R(N) is the right child of node N

Dept. of Data Science and AIML, A.I.T, CKM Page 19


Data Structures and Applications (BCS304) Module - 3

1. Preorder: Preorder is the procedure of visiting a node, traverse left and continue. When you cannot
continue, move right and begin again or move back until you can move right and resume.

Recursion function:

The Preorder traversal of a binary tree can be recursively defined as


 Visit the root
 Traverse the left subtree in preorder.
 Traverse the right subtree in preorder

In Figs (a) and (b), find the sequence of nodes that will be visited using pre-order traversal algorithm.

2. Inorder: Inorder traversal calls for moving down the tree toward the left until you cannot go further.
Then visit the node, move one node to the right and continue. If no move can be done, then go back one
more node.

Recursion function:
The inorder traversal of a binary tree can be recursively defined as
 Traverse the left subtree in inorder.
 Visit the root.
 Traverse the rig

Dept. of Data Science and AIML, A.I.T, CKM Page 20


Data Structures and Applications (BCS304) Module - 3

For the trees given in below, find the sequence of nodes that will be visited using in-order traversal
algorithm.

3. Postorder: Postorder traversal calls for moving down the tree towards the left until you can go no
further. Then move to the right node and then visit the node and continue.

Recursion function:
The Postorder traversal of a binary tree can be recursively defined as
 Traverse the left subtree in postorder.
 Traverse the right subtree in postorder.
 Visit the root

Dept. of Data Science and AIML, A.I.T, CKM Page 21


Data Structures and Applications (BCS304) Module - 3

For the trees given in below, find the sequence of nodes that will be visited using post-order traversal
algorithm.

4. Iterative inorder Traversal:

Iterative inorder traversal explicitly make use of stack function.


The left nodes are pushed into stack until a null node is reached, the node is then removed from the stack
and displayed, and the node’s right child is stacked until a null node is reached. The traversal then
continues with the left child. The traversal is complete when the stack is empty.

Dept. of Data Science and AIML, A.I.T, CKM Page 22


Data Structures and Applications (BCS304) Module - 3

6. Level-Order traversal:
7.
Visiting the nodes using the ordering suggested by the node numbering is called level ordering traversing.
The nodes in a tree are numbered starting with the root on level 1 and so on.

Firstly visit the root, then the root’s left child, followed by the root’s right child. Thus continuing in this
manner, visiting the nodes at each new level from the leftmost node to the rightmost node.

Level order traversal: 1 2 3 4 5

Initially in the code for level order add the root to the queue. The function operates by deleting the node at
the front of the queue, printing the nodes data field and adding the nodes left and right children to the
queue.

Expression Trees

Binary trees are widely used to store algebraic expressions. For example, consider the algebraic
expression given as:

Dept. of Data Science and AIML, A.I.T, CKM Page 23


Data Structures and Applications (BCS304) Module - 3

Given an expression, Exp = ((a + b) – (c * d)) % ((e ^f) / (g – h)), construct the corresponding binary tree.

e f g h
e
e
e
Given the binary tree, write down
e the expression that it represents.
e
e
e
e

Given the expression, Exp = a + b / c * d – e, construct the corresponding binary tree.

Use the operator precedence chart to find the sequence in which operations will be performed. The given
expression can be written as

Dept. of Data Science and AIML, A.I.T, CKM Page 24


Data Structures and Applications (BCS304) Module - 3

THREADED BINARY TREE

The limitations of binary tree are:


 In binary tree, there are n+1 null links out of 2n total links.
 Traversing a tree with binary tree is time
consuming. These limitations can be overcome by threaded
binary tree.

In the linked representation of any binary tree, there are more null links than actual pointers. These
null links are replaced by the pointers, called threads, which points to other nodes in the tree.

To construct the threads use the following rules:

1. Assume that ptr represents a node. If ptr→leftChild is null, then replace the null link
with a pointer to the inorder predecessor of ptr.
2. If ptr →rightChild is null, replace the null link with a pointer to the inorder successor ofptr.
Ex: Consider the binary tree as shown in below figure:

Figure A: Binary Tree


There should be no loose threads in threaded binary tree. But in Figure B two threads have been
left dangling: one in the left child of H, the other in the right child of G.

Figure B: Threaded tree corresponding to Figure A

In above figure the new threads are drawn in broken lines. This tree has 9 node and 10 0 -links which
has been replaced by threads.

Dept. of Data Science and AIML, A.I.T, CKM Page 25


Data Structures and Applications (BCS304) Module - 3

When trees are represented in memory, it should be able to distinguish between threads and
pointers. This can be done by adding two additional fields to node structure, ie., leftThread and
rightThread
 If ptr→leftThread = TRUE, then ptr→leftChild contains a thread, otherwise it contains a
pointer to the left child.
 If ptr→rightThread = TRUE, then ptr→rightChild contains a thread, otherwise it contains a
pointer to the right child.

Node Structure:
The node structure is given in C declaration

typedef struct threadTree *threadPointertypedef struct{


short int leftThread; threadPointer
leftChild;char data;
threadPointer rightChild; short int
rightThread;
}threadTree;

The complete memory representation for the tree of figure is shown in Figure C

Dept. of Data Science and AIML, A.I.T, CKM Page 26


Data Structures and Applications (BCS304) Module - 3

The variable root points to the header node of the tree, while root →leftChild points to thestart
of the first node of the actual tree. This is true for all threaded trees. Here the problem of the loose
threads is handled by pointing to the head node called root.

Inorder Traversal of a Threaded Binary Tree

 By using the threads, an inorder traversal can be performed without making use of astack.
 For any node, ptr, in a threaded binary tree, if ptr→rightThread =TRUE, the inorder
successor of ptr is ptr →rightChild by definition of the threads. Otherwise we obtain the
inorder successor of ptr by following a path of left-child links from the right-
child of ptr until we reach a node with leftThread = TRUE.
 The function insucc ( ) finds the inorder successor of any node in a threaded tree
without using a stack.

threadedpointer insucc(threadedPointer tree)


{ /* find the inorder successor of tree in a threaded binary tree */
threadedpointer temp;
temp =
tree→rightChild; if
(!tree→rightThread)
while (!temp→leftThread)
temp = temp→leftChild;
return temp;
Program: Finding inorder successor of a node

To perform inorder traversal make repeated calls to insucc ( ) function

void tinorder (threadedpointer tree)


{
Threadedpointer temp =
tree;for(; ;){
temp = insucc(temp);
if (temp == tree) break;printf(“%3c”, temp→data
}
}
Program: Inorder traversal of a threaded binary tree

Dept. of Data Science and AIML, A.I.T, CKM Page 27

You might also like