SlideShare une entreprise Scribd logo
1  sur  212
Data Structure using
‘C’
Module - II
Prepared by:
Smruti Smaraki Sarangi
Asst. Professor
School of Computer Application
IMS Unison University, Dehradun
Contents: TREE
 Tree
 Tree Terminologies
 Binary Tree
 Types of Binary Tree
 Tree Traversal Methods
 Expression Tree
 Binary Search Tree
 Threaded Binary Tree
 Heap Tree
 Height Balance or AVL Tree
 B-Tree, Decision Tree and B+- Tree
 Symbol Table Construction
Contents: Graph
 Graph
 Graph Terminologies
 Grap
 Expression Tree
 Binary Search Tree
 Threaded Binary Tree
 Heap Tree
 Height Balance or AVL Tree
 B-Tree, Decision Tree and B+- Tree
 Symbol Table Construction
Tree:
 A tree is a non-linear data structure where items
are having hierarchical relationships.
 It is a data structure in which each element is
attached to one or more elements directly beneath
it.
 The basic difference between a natural tree and a
tree in data structure is that natural tree grows
from ground to the air where as tree in data
structure grows from top to bottom.
 The general tree ‘T’ is a finite non-empty sets
whose elements called nodes. One of this element
is called root and the remaining elements of any
are partitioned into trees which are called the sub-
tree of tree ‘T’.
 The elements at the highest level of hierarchy is
the root.
A
DCB
JIHGFE
Tree Terminologies:
 Node: Each element of a tree is called a node. It
is the basic structure in a tree. There are 10
nodes in the above diagram.
 Root: It is specially designated node in a tree, it
is the first node in the hierarchical arrangement
of data items. Here ‘A’ is the root node.
 Parent Node: Parent of a node is the immediate
predecessor of a node. E.g.: Here ‘B’ is the
parent of ‘E’ and ‘F’.
 Child Node: Each immediate successor of a
node is referred as child. E.g.: Here, ‘H’, ‘I’, ‘J’
are child nodes of ‘D’
 Siblings: The child nodes belong to a single
parent are known as siblings. E.g.: Here, ‘E’ and
‘F’ are siblings because they have a single parent
‘B’.
 Level of the tree: The root of a tree is at level ‘0’.
Its children are at level ‘1’ and the sub-children of
the children of the root are at level ‘2’ and so on.
 Degree of an element/node: The number of sub-
trees of a given node is called the degree of the
node or the degree of an element or node is the
number of children it has. A terminal node is
called leaf node and the degree of a leaf node is
‘0’. E.g.: Here, ‘B’ has degree ‘2’, ‘C’ has degree
‘1’ and ‘F’ has no degree or degree ‘0’.
 Degree of a tree: The maximum degree of nodes in
a given tree is called the degree of a tree. In above
tree, the maximum degree of ‘A’ and ‘D’ is ‘3’. So
the degree of the tree is ‘3’.
 Terminal Node: A node with degree ‘0’ is called
leaf node or terminal node. E.g.: Here, ‘E’, ‘F’, ‘G’,
‘H’, ‘I’, ‘J’ are the leaf nodes.
 Edge: It is a connecting line between two nodes.
E.g.: ‘BE’ is an edge.
 Path: Path is a sequence of consecutive edges from
source node to destination node. In above tree, the
path between ‘A’ to ‘J’ is given by node pairs (A, D)
and (D, J). A path ending in a leaf is called a branch.
E.g.: AE, AF, AG, AI, AJ are branches.
 Depth of a tree: The depth of Node ‘X’ is the
length of unique path from root to Node ‘X’. Thus
root is at depth ‘0’. In the above tree, depth of ‘E’
is 2 and depth of ‘B’ is ‘1’.
 Height of the tree: The height of Node ‘X’ is the
longest path from the Node ‘X’ to the leaf node.
So all the leaf nodes are at height ‘0’. In above
tree, height of ‘B’ is ‘1’ and height of ‘J’ is ‘0’.
 Ancestor and Descendant: If there is a path from
node ‘N1’ to ‘N2’ then ‘N1’ is an ancestor of ‘N2’
and ‘N2’ is the descendant of ‘N1’. E.g.: In the
above tree ‘A’ is ancestor of ‘G’ and ‘C’ and ‘G’
and ‘C’ are descendant of ‘A’.
 Forest: A forest is a set of isolated tree or disjoint
tree. A set of trees is called Forest. Here after
deleting the root ‘A’, remaining are called Forest.
A
DCB
JIHGFE
DCB
JIHGFE
Note:
 Root node does not have parent node.
 A node has no children is called leaf node.
 A tree having ‘N’ nodes would have N – 1 edges.
 There will be exactly one path between the root
and any other node in the tree.
 The nodes with at least one child are called as
non-terminal or internal nodes.
 Terminal nodes are called external or leaf nodes.
Binary Tree:
 A Binary tree ‘T’ is defined as a finite set of
elements or data items, called nodes, such that:
 ‘T’ is empty, called the null tree or empty tree.
 ‘T’ contains a distinguished node ‘R’ called root of the
‘T’, and the remaining nodes of ‘T’ from an ordered pair
of disjoint binary trees ‘T1’ and ‘T2’ which are called
left sub-tree and the right sub-tree respectively.
 The general tree is never empty. The tree can
contain any number of children. But binary tree
has almost 2 child.
 If ‘T1’ is non-empty, then its root is called the left
successor of ‘A’. Similarly if ‘T2’ is non-empty,
then the root is called the right-successor of ‘A’.
 Binary trees ‘T’ and ‘Tꞌ’ are said to be similar, if
they have same structure and same set. The trees
are said to be copies, if they are similar and if they
have the same elements contained at the
corresponding
A
CB
HG
F
ED
JI
 The tree does not contains a root ‘R’ then two tree
‘T1’ and ‘T2’ are called respectively the left sub-
tree and right sub-tree of ‘R’
 Here, (1) and (3) are copies and (1) and (4) are
similar.
A
B
DC
E
F
HG
E
F
HG
A
B
DC
1 2 3 4
Binary Tree Vs Tree:
Binary Tree
 A binary tree can be
empty.
 Each element in a binary
tree having almost two
sub-trees (one or both
these sub-trees may be
empty.
 The sub-trees of each
element in a binary tree
are ordered.
Tree
 A tree can not be
empty.
 Each element in a
tree can have any
number of sub-
trees.
 These sub-trees of
tree are unordered.
Types of Binary Tree:
 Strictly Binary Tree: If every non-leaf node in
a binary tree has non-empty left and right sub-
trees, the tree is termed as a strictly binary tree.
A strictly binary tree with ‘n’ leaves always
contains 2n – 1 nodes.
A
CB
GFED
JI
 Full Binary Tree: A Binary tree ‘T’ is called
Full, if it is having maximum number of nodes
in all its levels.
A
CB
GFED
 Complete Binary Tree:
Complete Binary tree means that
the elements have 2 nodes. The
tree ‘T’ is said to be complete if
all its levels except possibly
nodes and if all the nodes at last
level appear as far left as possible.
 A binary tree of depth ‘d’ is an
almost complete binary tree, if
 Each leaf in the tree is either at level
‘d’ or at level ‘d – 1’.
 For any node ‘n’, in the tree with a
right descendant at level ‘d’, all the
left descendants of ‘n’, that are leaves
are also at level ‘d’.
A
CB
GFED
JI K
 Extended Binary Tree: A binary tree ‘T’ is said
to be 2-tree or an extended binary tree of each
node ‘n’ has either 0 or 2 children. In such a case
the node with 2 children are called internal nodes
and nodes with zero children are called external
nodes.
(1)
1
2 3
6
54
(2)
 Skew Binary Tree: A tree having only one path
which contains h + 1 number of nodes, if ‘h’ is
the height.
A
B
D
C
(1)
A
B
D
C
(2) E
Memory Representation of Binary Tree:
 There are two common methods used for
representing a binary tree.
 Sequential Representation using array
 Linked Representation using linked list with pointers.
Array Representation of Binary Tree:
 An one dimensional array can be used to represent
a binary tree in the memory. Here, we consider that
root is present at index 0. Assume tree[N] is an
array representing binary tree. If ‘i’ be index, then
 Root node is stored at index 0. i.e. root is at tree[0].
 Left child is stored at tree[2 * i + 1].
 Right child is stored at tree[2 * i + 2].
Drawbacks of Array Representation :
 While representing a binary tree in the form of an
array, most of the memory blocks in the middle
will be left blank or unused if the tree is not a
complete binary tree.
10
3020
605040
9080
0
4
1 2
70
3
5
7 11 12
10 20 30 40 50 60 70 80 90
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Linked Representation of Binary Tree:
 A binary tree can be represented by using linked
list, where each node is divided into 3 parts as:
 Info: it is used to store the information.
 Left: it is a pointer that holds the address of left child.
 Right: it is a pointer that holds the address of right child.
 If any sub-tree of a node is empty, then its
corresponding pointer of the node contains NULL,
indicating absence of sub-tree.
Left Info Right
root
A
B C
XEXDX HXGX
XJ XKXXFX
XLX
Construction of General Tree to
Binary Tree:
 It is convenient to represent binary tree than
representing general tree in a program, because in
case of general tree, the number of edges
connected from a node at any given time is
unpredictable.
 Therefore the node space has to be managed in
such a way that each node is allowed a variable
number of sub-tree pointers.
 In case of binary tree each node has predictable
maximum of two sub-tree pointers.
 A general tree can be converted into an
equivalent binary tree. The conversion process is
called the natural correspondence between
general and binary trees. The procedure is:
 Insert edges connecting siblings from left to right at the
same level.
 Delete all edges of a parent to its children expect to its
left most offspring.
 Rotate the resultant tree 45o to mark clearly left and
right sub-trees.
Example:
 Initial transformation of general tree as shown
below:
A
B C D
FE HG JI
ML
K
 Binary tree corresponding to general tree is:
A
B C D
FE HG JI
ML
K
A
B
C
D
F
E
H
G
J
I
M
L
K
Traversal of Binary Tree:
 The process of visiting each node of the tree
exactly once is called tree traversal. The traversal
of a binary tree involves three basic activities,
such as:
 Visiting the root.
 Traverse the left sub-tree.
 Traverse the right sub-tree.
 The above tree traversal methods can be
implemented in two ways. That are:
 Recursive Tree Traversal
 Non-Recursive Tree Traversal
 The three basic activities are done in different
order. There are three types of traversal methods
used. That is:
 Pre-order traversal (RLTRT)
 In-order traversal (LTRRT)
 Post-order traversal (LTRTR)
Recursive Binary Tree Traversal:
 The tree will be traversed in the following order:
 Visit the root
 Traverse the left sub-tree in pre-order.
 Traverse the right sub-tree in pre-order.
 The algorithm for this is:
Pre-Order(Node)
Step 1: if Node != Null, then
Step 1.1: Process(Node)
Step 1.2: Pre-Order(Left-child[Node])
Step 1.3: Pre-Order(Right-child[Node])
[End of if]
Step 2: Exit
Pre-Order Traversal (RLTRT):
 The tree will be traversed in the following order:
 Traverse the left sub-tree in in-order.
 Visit the root
 Traverse the right sub-tree in in-order.
 The algorithm for this is:
In-Order(Node)
Step 1: if Node != Null, then
Step 1.1: In-Order(Left-child[Node])
Step 1.2: Process(Node)
Step 1.3: In-Order(Right-child[Node])
[End of if]
Step 2: Exit
In-Order Traversal (RLTRT):
 The tree will be traversed in the following order:
 Traverse the left sub-tree in post-order.
 Traverse the right sub-tree in post-order.
 Visit the root
 The algorithm for this is:
Post-Order(Node)
Step 1: if Node != Null, then
Step 1.1: Post-Order(Left-child[Node])
Step 1.2: Post-Order(Right-child[Node])
Step 1.3: Process(Node)
[End of if]
Step 2: Exit
Post-Order Traversal (RLTRT):
 The Pre-Order Traversal is: ABDECFG
 The In-Order Traversal is: DBEAFCG
 The Post-Order Traversal is: DEBFGCA
Example:
A
CB
GFED
Pre-Order(root)
 Step 1: Let PTR = root
 Step 2: Repeat while PTR != NULL
 Step 2.1: Process INFO[PTR]
 Step 2.2: if RIGHT[PTR] != NULL, then
PUSH(RIGHT[PTR])
 Step 2.3: if LEFT[PTR] != NULL, then
PTR = LEFT[PTR]
 Step 2.4: else PTR = POP()
[End of if]
[End of while]
 Step 3: Exit
Non-Recursive Pre-Order Traversal:
In-Order(root)
 Step 1: Let PTR = root
 Step 2: Repeat while PTR != NULL
 Step 2.1: PUSH(PTR)
 Step 2.2: PTR = LEFT[PTR]
[End of while]
 Step 3: Set PTR = POP()
 Step 4: Repeat while PTR != NULL
 Step 4.1: Process INFO[PTR]
 Step 4.2: if RIGHT[PTR] != NULL, then PTR = RIGHT[PTR]
GOTO Step 2
[End of if]
 Step 4.3: PTR = POP()
[End of while]
 Step 5: Exit
Non-Recursive In-Order Traversal:
Post-Order(root)
 Step 1: Let PTR = root
 Step 2: Repeat while PTR != NULL
 Step 2.1: PUSH(PTR)
 Step 2.2: if RIGHT[PTR] != NULL, then PUSH(RIGHT[PTR])
[End of if]
 Step 2.3: PTR = LEFT[PTR]
[End of while]
 Step 3: PTR = POP()
 Step 4: Repeat while PTR > 0 and PTR != NULL
 Step 4.1: Process INFO[PTR]
 Step 4.2: PTR = POP()
[End of while]
 Step 5: if PTR < 0 AND PTR != NULL, then
 Step 5.1: Set PTR = - PTR
 Step 5.2: GOTO Step 2
 Step 6: Exit
Non-Recursive Post-Order Traversal:
Construction of a Binary Tree:
 A binary tree can be constructed by using a
combination of tree traversal methods, such as:
 Pre-order and In-order Traversal
 Post-order and In-order Traversal
 Pre-order and Post-order Traversal
Construction of a Binary Tree Using
Pre-order and In-Order Traversal:
Procedure:
 Step 1: First node of the Pre-order traversal is the root node
of the tree.
 Step 2: Find the position of the root node in the in-order
traversal.
 Nodes proceeding the root in the In-order, construct the
left sub-tree.
 Nodes succeeding the root in the In-order, construct the
right sub-tree.
 Step 3: Find out the next roots for each sub-trees using pre-
order
 Step 4: Continue the above process until leaf nodes are
found.
Example:
 Construct a binary tree from the given pre-order
and in-order tree traversal.
Pre-order: ABDEHICFG and
In-order: DBHEIAFCG.
Here, Root = A for the tree. For sub-trees of root A,
the node ‘B’, ‘C’ and ‘E’ are the roots.
A
B C
D E F G
H I
DBHEI FCG
HEI
 The first node in pre-order traversal is the root
node of the tree. Here, ‘A’ is the root.
 Find the position of root node ‘A’ in in-order
traversal.
 The nodes preceding the root node in the in-order
traversal are the nodes of the left sub-tree of the
root node i.e. DBHEI and the nodes succeed to
the root node are the nodes in the right sub-tree of
the node FCG.
 Now take two sets of in-order and pre-order
traversals of the left and right sub-trees of the
root.
 The first set is the nodes appear precede to the
root node in in-order traversal i.e. DBHEI and the
combination of those nodes only appear in pre-
order traversal just after the root node. i.e.
BDHEI.
 The second set is the nodes appear in in-order
traversal i.e. FCG and the nodes in the pre-order
traversal except the root node and the nodes
considered in the first set i.e. CFG.
 Considering these two sets of pre-order and in-
order traversals for the left and right sub-trees we
can repeat step - 2 and step - 3 till the entire tree
is constructed.
Construction of a Binary Tree Using
In-order and Post-Order Traversal:
Procedure:
 Step 1: Here, last node in the Post-order traversal is
considered as root node of the tree.
 Step 2: Find the position of the root node in the in-order
traversal.
 Nodes preceding the root in the In-order, construct the
left sub-tree.
 Nodes succeeding the root in the In-order, construct the
right sub-tree.
 Step 3: Find out the next roots for each sub-trees using
post-order
 Step 4: Continue the above process until leaf nodes are
found.
Example:
 Construct a binary tree from the given post-order
and in-order tree traversal.
Pre-order: DHIEBFGCA and
In-order: DBHEIAFCG.
Here, Root = A for the tree. For sub-trees of root A,
the node ‘B’, ‘C’ and ‘E’ are the roots.
A
B C
D E F G
H I
DBHEI FCG
HEI
 The last node in post-order traversal is the root
node of the tree. Here, ‘A’ is the root.
 Find the position of root node ‘A’ in in-order
traversal.
 The nodes preceding the root node in the in-order
traversal are the nodes of the left sub-tree of the
root node i.e. DBHEI and the nodes succeed to
the root node are the nodes in the right sub-tree of
the node FCG.
 Now take two sets of in-order and post-order
traversals of the left and right sub-trees of the
root.
 The first set is the nodes appear preceding to the
root node in in-order traversal i.e. DBHEI and the
combination of those nodes only appear in post-
order traversal just before the root node. i.e.
DHIEB.
 The second set is the nodes appear after the root
node is in-order traversal i.e. FCG and the nodes
in the post-order traversal except the root node
and the nodes considered in the first set i.e. FGC.
 Considering these two sets of post-order and in-
order traversals for the left and right sub-trees
step - 2 and step – 3 is repeated till the entire tree
is constructed.
Construction of a Binary Tree Using
Pre-order and Post-Order Traversal:
 Construct a binary tree from the given pre-order
and post-order tree traversal.
Pre-order: ABDEHICFG
Post-order: DHIEEBFGCA
A
B C
D E F G
H I
DHEI and
DHIE , B = x1
FG, C= x2
HEI
 The first node of pre-order traversal and last node
of post-order traversal is considered as root of the
tree.
 Find the node succeeding the root node in pre-
order, say x1 and the node preceding the root node
in post-order say x2.
 If x1 = x2, then it can be taken as left or right child of
root and which may not result unique tree
 If x1 != x2, then x1 is taken as left child i.e. B, and x2 is
taken as right child i.e. C of root node.
 Find the position of x2, i.e. ‘C’ in pre-order and
position of x1 i.e. ‘B’ in the post-order.
 Consider two sets of pre-order and post-order traversal
of left and right sub-tree of root.
 The first set consists of nodes that are present after
x1 and before x2 in pre-order traversal i.e. DEHI
and the nodes present before x1 in post-order i.e.
DHIE.
 The second set consists of nodes that are present
after x2 in pre-order traversal i.e. FG and the nodes
present after x1 and before x2 in post-order
traversal i.e. FG.
 By taking 2 sets of pre-order and post-order
traversals from left and right sub-trees, repeat
steps-2 and 3 to construct the entire tree.
Expression Tree:
 It is a binary tree, which stores an arithmetic
expression. The leaf nodes of the expression tree
are always operands and all other internal nodes
are the operators, including the root. Divide and
conquer technique used to convert an expression
into a binary tree.
 E.g. (a + b + c) * ((d – e) / (f + g – h))
*
+ /
h
g
+d e
-
f
-
c
ba
+
 Precedence Table:
Brackets innermost: Highest level
^ (exponential) : Higher level
* and / : Middle level
+ and - : Lowest level
Procedure for constructing an
Expression Tree:
 Find out the prefix or postfix notation of given infix
expression.
 Identify the root of the expression tree using prefix (1st
symbol) or postfix notation (last symbol).
 Identify root in the infix and identify left sub-tree,
right sub-tree.
 Find the next root nodes of each sub-trees in infix
notation.
 Continue this process until leaf nodes exist.
Note: Here, we will find all the leaf nodes are the
operands all the internal nodes are the operators.
E.g.: Infix: (A+B*(D – E/F)), Prefix: -+A*B – D / EF
Construction of an expression tree
from a postfix expression:
 Step 1: Scan each symbol from the postfix expression.
 Step 2: If an operand is found, then create a one node
tree and push a pointer to it onto the stack.
 Step 3: If an operator is found, then POP two pointers
belonging to two trees say T1 and T2 from stack and
construct a tree where root is the operator, T2 is left
sub-tree and T1 is right sub-tree respectively.
 Step 4: PUSH the pointer to the above resultant sub-
tree onto STACK.
 Step 5: Exit.
[Where an expression ‘E’ in postfix notation
appended with ‘)’, a special symbol as delimiter.
Assume GETSYMBOL() is a procedure for
scanning a symbol from expression ‘E’,
GETNODES() is for creating a new node].
Step 1: SYMBOL = GETSYMBOL(E)
Step 2: Repeat while SYMBOL != ‘)’
Step 2.1: if SYMBOL = OPERAND, then
NEW = GETNODE(NODE)
INFO[NEW] = SYMBOL
PUSH(NEW)
Algorithm:
Step 2.2: else
Step 2.2.1: if SYMBOL = OPERATOR,
then PTR1 = POP()
PTR2 = POP()
NEW = GETNODE(NODE)
INFO[NEW] = SYMBOL
LEFT[NEW] = PTR2
RIGHT[NEW] = PTR1
PUSH(NEW)
[End of if]
[End of if]
SYMBOL = GETSYMBOL(E)
[End of while]
Step 3: Exit
Example on Construction of
Expression Tree:
 Construct an expression tree for the postfix
expression: ABC * + DE ^ /
 Solution: Given expression is : ABC * + DE ^ /.
Now add ‘)’ at the end of the given postfix
expression. So, the expression becomes as:
ABC*+DE^/).
 Scan each symbol from left to right in postfix
expression. When the symbol is operand then
create a one node tree and push its address into
stack. When the symbol is operator, then POP two
addresses into pointers T1 and T2 respectively.
 Construct a tree where root is the operator, T2 is
left sub-tree and T1 is the right sub-tree. Push the
root address of the resultant tree into stack.
 Scan ‘A’: Scan ‘B’:
 Scan ‘C’:
A BA
A CB
 Scan ‘*’: Scan ‘+’:
 Scan ‘D’:
A *
CB
+
*
CB
A
+
*
CB
A
D
 Scan ‘*’: Scan ‘^’:
 Scan ‘/’:
 This the final expression tree.
+
*
CB
A
D E +
*
CB
A
^
ED
/
^
ED
+
*
CB
A
EVAL_EXP_TREE(ROOT, VAL)
Step 1: PTR = ROOT
Step 2: if PTR != NULL, then
Step 2.1: PTR1 = LEFT[PTR]
Step 2.2: PTR2 = RIGHT[PTR]
Step 2.3: if INFO[PTR] != OPERATOR, then
T1 = INFO[PTR1]
Step 2.4: else
T1 = EVAL_EXP_TREE(PTR1, VAL)
[End of if]
Algorithm for Evaluation of Expression
Tree:
Step 2.5: if INFO[PTR2] != OPERATOR, then
T2 = INFO[PTR2]
Step 2.6: else
T2 = EVAL_EXP_TREE(PTR2, VAL)
Step 2.7: OPERATOR = INFO[PTR]
Step 2.8: VALUE = T1 OPERATOR T2
Step 2.9: RETURN(VAL)
[End of if]
Step 3: Exit
Binary Search Tree (BST):
 A binary tree ‘T’ is termed as binary search tree,
if each node ‘n’ of ‘T’ satisfies the following
properties.
 The value of ‘n’ is greater than the values of all nodes
in its left sub-tree and
 The value of ‘n’ is less than the values of all nodes in
its right sub-tree.
 A binary search tree is useful for binary search.
Construction of Binary Search Tree:
 While constructing a BST, initially, we store the
first node as Root node and then we follow
insertion of a node based on the rules of BST. So,
for each insertion, we need to search for
appropriate node either left or right based on the
value of the node to be inserted.
 E.g.: Construct a BST with the following input
values: 70, 20, 11, 45, 95, 76, 29, 59, 99
76
70
9520
11 9945
29 59
Algorithm for insertion into BST:
Insert_BST(Root, Left, Right, Info, Item, Avail)
[Allocates the memory for Fresh node and initialize
Info part of the node with Item.]
Step 1: Fresh = Avail
Step 2: Info[Fresh] = Item
Step 3: Left[Fresh] = NULL
Step 4: Right[Fresh] = NULL
Step 5: if Root = NULL, then Root = Fresh
Step 6: else
Step 6.1: PTR = Root
Step 6.2: Repeat while (PTR != NULL)
Step 6.2.1: if (Info[Fresh] < Info[PTR]),
then, PREV = PTR
PTR = Left[PTR]
Step 6.2.2: else
PREV = PTR
PTR = Right[PTR]
[End of if]
[End of while]
Step 6.3: if (Info[Fresh] < Info[PREV]), then
Left[PREV] = Fresh
Step 6.4: else Right[PREV] = Fresh
[End of if]
Step 7: Exit
Example:
 Using the algorithm , construct a BST, using the
following input values: 15, 21, 10, 5, 18, 13, 25,
11.
200 15 300
400 10 500 600 21 700
800 13 XX 5 X X 18 X
X 11 X
X 25 X
Root 100
100
200
600
300
700400 500
800
Deletion of Nodes from BST:
 While deleting nodes in a BST, the following list
comes into out mind. The node to be deleted can
be any one of the following types.
 Leaf nodes of a tree. (e.g. 20, 37, 65, 85 etc.)
 Internal node, which is connected with one
child/sub-tree i.e. either right or left. (e.g. 35,
45, 55, 80).
 Internal node, which is connected with two
child/sub-trees i.e. right and left. (e.g. 30, 90
etc.)
 Root of the tree. e.g. 50.
50
40 70
60
55
90
37
9565
9252
80
85
45
423520
30
Case 1:
 When leaf node is deleted e.g. 20
50
40 70
60
55
90
37
9565
9252
80
85
45
423520
30
Case 2.1:
 When an internal node with right child is deleted
e.g. 35
50
40 70
60
55
90
37
9565
9252
80
85
45
423520
30
Case 2.2:
 When an internal node with right child is deleted
e.g. 80
50
40 70
60
55
90
37
9565
9252
80
85
45
423520
30
Case 3.1:
 When an internal node with left child is deleted e.g.
95
50
40 70
60
55
90
37
9565
9252
80
85
45
423520
30
Case 3.2:
 When an internal node with right child is deleted
e.g. 55
50
40 70
60
55
90
37
9565
9252
80
85
45
423520
30
Case 4.1:
 When an internal node having left and right sub-
trees is deleted e.g. 90
50
40 70
60
55
90
37
9565
9252
80
85
45
423520
30
Case 4.2:
 When an internal node having left and right sub-
trees is deleted e.g. 60
50
40 70
60
55
90
37
9565
9252
80
85
45
423520
30
Case 4.3:
 When the root node is deleted i.e. 50
50
40 70
60
55
90
37
9565
9252
80
85
45
423520
30
Root
Algorithm for Deletion in BST:
DEL_BST(Root, Left, Right, Info, Item)
[Assume a BST whose root node is identified by a
pointer Root, Left and Right identifies the address
of left and right nodes. Item is the info of the node
to be deleted]
 Step 1: if Root = NULL, then
Display “Underflow”
Return
[End of if]
 Step 2: PTR = Root
 Step 3: Repeat while PTR != NULL and
Info[PTR] != Item
Step 3.1: if Item < Info[PTR], then
PREV = PTR
PTR = Left[PTR]
Step 3.2: else
PREV = PTR
PTR = Right[PTR]
[End of if]
[End of while]
//At the end of the Step – 3, either PTR = NULL or
Node with Info = Item is found.
 Step 4: if PTR = NULL, then
Display “Item not found”
Return
//To delete leaf node
 Step 5: elseif(Left[PTR] = NULL AND
Right[PTR] = NULL), then
Step 5.1: if Item < Info[PREV], then
Left[PREV] = NULL
Step 5.2: else
Right[PREV] = NULL
[End of if]
//To delete internal node with right child
 Step 6: elseif(Left[PTR] = NULL AND Right[PTR]
!= NULL), then
Step 6.1: if Item < Info[PREV], then
Left[PREV] = Right[PTR]
Step 6.2: else
Right[PREV] = Right[PTR]
[End of if]
//To delete internal node with left child
• Step 7: elseif(Right[PTR] = NULL AND
Left[PTR] != NULL), then
Step 7.1: if Item < Info[PREV], then
Left[PREV] = Left[PTR]
Step 7.2: else
Right[PREV] = Left[PTR]
[End of if]
//To delete Root node of the tree
• Step 8: elseif (PTR = Root), then
Step 8.1: if(Left[Root] = NULL AND Right[Root] =
NULL), then
Root = NULL
Step 8.2: else
P1 = Right[PTR]
Repeat while(Left[P1] != NULL)
P1= Left[P1]
[End of while]
Left[P1] = Left[Root]
Root = Right[Root]
[End of if]
//To delete internal node with two child trees
• Step 9: else
Step 9.1: P1= Right[PTR]
Step 9.2: Repeat while(Left[P1] != NULL)
P1 = Left[P1]
[End of while]
Step 9.3: Left[P1] = Left[PTR]
Step 9.4: if (Item < Info[PREV]), then
Left[PREV] = Right[PTR]
Step 9.5: else
Right[PREV] = Right[PTR]
[End of if]
[End of if – Step – 4]
• Step 10: Exit
Threaded Binary Tree:
 In linked representation of binary tree, the number
of NULL links or NULL pointers are actually
more than Non-NULL pointers.
 Here in given figure, a binary tree consists of 6
nodes, where total NULL pointers are 7 and
Actual pointers/Non-NULL pointers are 5.
 A binary tree with ‘N’ nodes has:
Total Pointers = 2N
NULL Pointer = N + 1
Non – NULL Pointers = N - 1
200 15 300
400 10 500 X 21 X
800 13 XX 5 X
X 11 X
Root 100
100
200 300
400 500
800
 A. J. Perlis and C. Thornton jointly proposed an
idea to make use of NULL pointers, which will be
replaced with special pointers called threads.
 A binary tree with such pointers or threads is
called threaded binary tree.
 The advantages of threaded binary tree is that
traversal, insertion and deletion operations can be
performed without using either stack or recursion.
 The threads in a tree diagram of threaded binary
tree are usually indicated by dotted lines.
 In a right-in threaded binary tree each right NULL
pointers is replaced by special pointers called r-
thread, to the in-order successor of that node.
 Similarly, in left-in-threaded binary tree each left
NULL pointer is replaced by a special pointer
called l-thread, to the in-order predecessor of that
node.
 An in-threaded binary tree may be defined as a
binary tree, which is both left-in-threaded and
right-in-threaded.
 A threaded binary tree is constructed from a
binary tree by taking any of the tree-traversal
methods. There are two types of threading. That
is:
 One way Threading
 Two way Threading
One way Threading:
 A threading will appear in left or right field.
 The thread is the left field will point to the
previous node in the in-order traversal of the tree.
This type of traversing is called left-in threading.
 The thread which appears in the right field will
point to the next node in the in-order traversal, this
is the right-in threading.
Two way Threading:
 In two-way threading, the thread appears in left
and right field. The left pointer of the first node
and right pointers of the last node will contain
NULL entries in their pointers.
 A header node is implemented where address is
tide by these two pointers and header node always
stores the address of the root node.
Constructing Threaded Binary Tree
using In-Order Traversal:
Procedure:
 Identify each node having NULL pointers.
 Find the position of identified nodes and their
adjacent nodes in in-order traversal.
 Input the appropriate thread value to point
 Point the dangling pointers to header node.
E.g. The in-order traversal of binary tree is:
DBEAFC A
B C
FED
 Here, according to the Adjacency of the nodes:
 Right link of ‘D’ is pointed to ‘B’
 Left link of ‘E’ is pointed to ‘B’
 Right link of ‘E’ is pointed to ‘A’
 Left link of ‘F’ is pointed to ‘A’
 Right link of ‘F’ is pointed to ‘C’
 Two dangling pointers i.e. left link of ‘D’ and right
link of ‘C’ are pointed to header
 So, the threaded binary tree for this is given
below:
A
B C
FED
Header
node
 The one way in-order threaded binary tree is:
Right –in threaded binary tree.
A
B
D E
C
HG
JF
L
K
 The two way in-order threaded binary tree is:
A
B
D E
C
HG
JF
L
K
 The two way threading with header node:
A
B
D E
C
HG
JF
L
K
Header Node
 When we represent threaded binary tree in
memory, each node structure is added with two
logic fields, l-thread and r-thread in order to
distinguish between actual pointers and threads.
The structure of node looks as follows:
 Here, l-thread and r-thread takes the values either
0 or 1.
 l-thread = 1, indicates left is a normal pointer
 l-thread = 0, indicates left is a thread
 r-thread = 1, indicates right is a normal pointer
 r-thread = 0, indicates right is a thread.
l-
thread
left info right r-thread
111
1 100 1100 111
100
1 200 1A 300
300
1 600 0C 111
200
1 400 1B 500
500
0 200 1E 100
111
0 111 0D 200
600
0 100 0F 300
Advantages of threaded binary tree:
 The traversing operation is more faster than that of
its unthreaded version, because with threaded
binary tree non-recursive implementation is
possible which can run faster and does not require
the botheration of stack management.
 We can efficiently determine the predecessor and
successor nodes starting from any node this is
more time consuming and default in case of
unthreaded binary tree.
 Any node can be accessible from any other node.
Threads are usually more to upward where as
links are downward. Thus, in a thread tree, one
can move in either direction and move only in
downward direction starting from root.
Heap Tree:
 A heap is defined as an almost complete binary
tree of ‘n’ nodes, such that the value of each node
is less than or equal to or greater than or equal to
the value of the father or parent node.
 A heap tree is defined as an almost complete
binary tree of ‘n’ nodes, where path from root
node to a terminal node forms an ordered list.
There are two types of heap trees. That is:
◦ Max Heap Tree/Descending Heap Tree
◦ Min Heap Tree/Ascending Heap Tree
Max Heap Tree/Descending Heap Tree:
 Max Heap Tree is the tree, where each parent
node contains the largest key value or equal key
value to its child nodes .
 Here path from root node to a terminal node
forms an ordered list of elements arranged in
descending order, with root node has largest key
value or equal key value to its child.
70
40
15 17
57109
50
20 10
Min Heap Tree/Ascending Heap Tree:
 Min Heap Tree is the tree, where each parent node
contains the smallest key value or equal key value
to its child nodes.
 Here path from root node to a terminal node
forms an ordered list of elements arranged in
ascending order, with root node has smallest key
value or equal key value to its child.
15
17
50 70
170100150120
20
60 40
Notes:
 Heap tree is useful in implementing the priority
queue, where elements can be inserted arbitrarily
but they are arranged in a heap.
 So, in ascending heap, elements can be deleted in
ascending priority queue order and in descending
heap, elements can be deleted in descending
priority queue manner.
Construction of Heap Tree:
 Procedure: Suppose ‘H’ is a heap with ‘N’ nodes
and assume Item is the value given and it is to be
inserted into heap ‘H’ as follows:
 First join Item at the end of ‘H’, so that ‘H’ becomes an
almost complete binary tree, but not necessarily a heap.
 Find the appropriate place for Item in ‘H’, So that ‘H’
finally becomes a heap.
 E.g.: Construct a Max Heap from the following
sequence of inputs: 45, 32, 50, 22, 65, 55, 77
 Insert 45: Insert 32: Insert 50:
45
3
2
4
5
3
2
4
5
5
0
3
2
5
0
4
5
 Insert 22:
 Insert 65:
 Insert 55:
3
2
5
0
4
5
2
2
3
2
5
0
4
5
2
2
65
6
5
5
0
4
5
2
2
32
5
0
6
5
4
5
2
2 32
5
0
65
4
5
2
2 32
5
5
5
0
65
5
5
2
2 32
4
5
 Insert 75:
 After inserting all nodes, the construction is
finished and the final max heap tree is:
5
0
65
4
52
2 32
5
5
5
0
65
7
72
2 32
4
5
77 55
5
0
77
6
52
2 32
4
5 55
5
0
77
6
5
2
2 32
4
5 55
Deleting the root of a heap:
 Suppose ‘H’ is a heap with ‘N’ elements and
suppose we want to delete the root ‘R’ of ‘H’.
This is accomplished as follows:
 Assign the root ‘R’ to some variable item.
 Replace the deleted node ‘R’ by the last node ‘L’ of ‘H’,
so that ‘H’ is still a complete tree, but not necessarily a
heap.
 Do the heap in the out come tree and again do the above
process.
Example:
 Delete 95:
55
95
85 70
6530
22
33
2015 15
55
22
85 70
653033
2015 15
55
85
22 70
653033
2015 15
 Delete 85:
22
85
55 70
653033
2015 15
22
15
55 70
653033
2015
 Delete 70:
22
70
55 15
653033
2015
22
85
55 65
153033
2015
22
20
55 65
153033
15
 Delete 65:
22
65
55 20
153033
15
22
65
55 30
152033
15
22
15
55 30
152033
 Delete 55:
22
55
15 20
153033
22
55
33 30
152015
22
15
33 30
2015
 Delete 33:
22
33
15 30
2015
15
33
22 30
2015
15
30
22 20
1515
20
22
30
15
 Delete 30:
 Delete 22
 Delete 20 Delete 15: Delete 15:
Nil
15
15
22 20
15
22
15 20
15
15 20
20
15 15
15
15
15
Height Balanced Tree/AVL Tree:
 In a binary search tree, the effectiveness of
searching process always depends upon how data
is organized to make up a specific tree.
 Searching in a binary search tree is efficient if the
heights of both left and right sub-tree of any node
are equal.
 Frequent insertion and deletion in binary search
tree is likely to make it unbalance.
 When a binary search tree is not balanced, the
operations like searching, insertion, deletion takes
considerable time as compared to a binary search
tree which is balanced.
 The efficiency of searching is ideal, if HL – HR ≤ 1,
where HL = left sub-tree and HR = right sub-tree.
Such a binary tree is called Balanced Binary Tree.
 Balance Factor of a node in binary search tree is the
difference between height of left sub-tree and height
of right sub-tree of it.
BF = HL – HR,
where BF = Balance Factor
HL = Height of left sub-tree
HR = Height of right sub-tree
So, a binary search tree is height balanced if all its
nodes have a balance factor within the range (-1, 0, 1).
So, for every node in a height balanced tree balance
factor BF є {-1, 0, 1}.
 It was invented in the year 1962, by two Russian
Mathematician ADELSON-VELSKII and
LANDIS. Hence, such tree is called AVL Tree.
 If the height of the right sub-tree is greater than
the left sub-tree then BF = -1, if same then BF = 0,
if height of value of left sub-tree is greater than
right sub-tree then BF = 1.
 E.g.: A
CB
D E
F
G
1
-1 -1
10 0
0
Insertion of a node in an AVL Tree:
 Case 1: Insertion of a node as a child of any non-
leaf node which has only one child. There will be
no effect in the tree.
A
CB
D E
F
GH
 Case 2: Insertion of a node as a child of left node
whose parent node has two children of the sub-
tree of shorter height there will be no effect on the
tree.
A
CB
D E GH
I K
 Case 3: Insertion of a node as a child of leaf node,
where parent node has level zero of sub-tree of
same height there will be no effect in the tree.
A
CB
D E GH
I
 Case 4: Insertion of a node as a child of leaf node
of sub-tree of larger height, then the AVL tree
become unbalanced and to make it balance we
have to perform rotation operation.
A
CB
D E GF
H
I
AVL Rotation:
 Assume a tree is balanced initially and the tree
becomes imbalanced due to insertion or deletion
of a node. Now, in order to make the tree balanced
we need to follow certain rotation methods.
 There are 4 types of AVL Rotations present.
 LL (Left to Left) Rotation
 RR (Right to Right) Rotation
 LR (Left to Right) Rotation
 RL (Right to Left) Rotation
 Pivot Node: Pivot node in a binary search tree is
the node where the tree gets imbalanced. That is,
node for which the balance factor |BF| > 1is
treated as pivot node.
LL (Left to Left) Rotation:
 When the tree gets imbalanced due to insertion of
a node at left of the left sub-tree of pivot node,
then we follow LL Rotation.
 This is the imbalance tree, after inserting a node at
sub-tree of node ‘C’. Here pivot node is ‘A’,
whose balance factor is 2.
A
C
B AR
CL
BR
CR
2
1
0
 Here, ‘CL’ is the left sub-tree of node ‘C’, ‘CR’ is
the right sub-tree of node ‘C’, ‘BR’ is the right
sub-tree of node ‘B’ and ‘AR’ is the right sub-tree
of node ‘A’.
 After the rotation of node ‘A’, node ‘A’, becomes
the right child of node ‘B’ and ‘BR’ becomes the
left child of node ‘A’ as shown below. After
rotation the tree becomes balanced.
C
B
CL CR
0
0 A
ARBR
0
RR (Right to Right) Rotation:
 When the tree gets imbalanced due to insertion of
a node at right of the right sub-tree of pivot node,
then we follow RR Rotation.
 After RR Rotation, the tree gets balanced.
A
C
BAL
CR
BL
CL
-2
-1
0
 Here, unbalanced pivot node ‘A’. ‘AL’ is the left
child of ‘A’, ‘BL’ is the left child of ‘B’, ‘CL’ is
the left child of ‘C’ and ‘CR’ is the right child of
‘C’
 After the Rotation at pivot node ‘A’, the balanced
tree is:
Where ‘A’ becomes the left child of ‘B’ and
‘BL’ becomes the right child of ‘A’.
A
B
AL BL
0
0 C
CRCL
0
LR (Left to Right) Rotation:
 When the tree gets imbalanced due to insertion of
a node at right of the left sub-tree of pivot node,
then we follow LR Rotation.
 This considered on two rotation. That is:
 RR rotation at point ‘B’
 LL rotation at pivot point ‘A’
A
B AR
+2
-1
0CBL
CL CR
 After performing the ‘RR’ Rotation at ‘B’ the
tree becomes:
 Since it imbalanced at pivot point ‘A’ we again
perform ‘LL’ Rotation at ‘A’. So final balanced
tree is:
A
B
C AR
BL
CR
CL
2
1
0
B
C
BL CL
0
0 A
ARCR
0
RL (Right to Left) Rotation:
 When the tree gets imbalanced due to insertion of
a node at left of the right sub-tree of pivot node,
then we follow RL Rotation.
 Here, to balance the tree, we perform two rotation.
 LL rotation at point ‘B’
 RR rotation at pivot point ‘A’
A
BAL
-2
1
0 C BR
CRCL
 After performing the ‘LL’ Rotation at point ‘B’
the tree becomes:
 This is not balanced. So to make it balance again
perform RR rotation at point ‘A’. So, the final
tree becomes:
A
B
CAL
BR
CL
CR
-2
-1
0
B
C
AL CL
0
0 A
BRCR
0
Example on Building an AVL Tree:
 Construct an AVL Tree from the following
sequence of inputs. That is: 50, 60, 70, 15, 10, 33,
22, 35, 25, 40.
 Insert 50:
: No balancing required.
 Insert 60:
: No balancing required.
50
0
50
-1
60 0
 Insert 70:
 Insert 15:
: No balancing required
RR Rotation50
-2
60 -1
70
0
50
60
70
0
0
0
50
60
70 0
1
1
150
 Insert 10:
 Insert 33:
50
60
70 0
2
2
151
100
LR Rotation
15
60
70 0
1
0
100 050
15
60
70 0
2
-1
100 150
33 0
LR Rotation
15
50
60
-1
0
0
10
0
033 700
 Insert 22:
: No Balancing required
 Insert 35:
: No Balancing required
15
50
60
-1
1
-1
10
0
133 70 0
22
0
15
50
60
-1
1
-1
10
0
033 70 0
22
0
035
 Insert 25:
 Insert 40:
15
50
60
-1
2
-2
10
0
133 70 0
22
-1
035
025
RL Rotation 22
50
60
-1
1
0
151 033 70 0
25
0
035100
LR Rotation
22
50
60
-1
2
-1
151
-133 70
0
25
0
-1
3510
0 40 0
22
33
50
00
1
151
-1
25 60
0
40
0
-1
35
10
0
70
0
Balanced M-way Binary Search
Tree/B-Tree:
 A node of the tree may contain many records or
key and pointers to children. A binary tree is also
known as balanced sort tree.
 It finds its use in external sorting. It is not a binary
tree. To reduce the disk space, accesses and several
conditions of the tree must be considered. i.e.
 The height of the tree must be kept to a minimum
 There must be no empty sub-tree above the leaves of tree.
 The leaves of the tree must all be on the same levels
 All nodes excepts the leaves must have at least same
minimum number of children.
Characteristics of B-Tree:
 B-Tree of order ‘M’ has the following properties.
 Each node has a maximum of ‘M’ children and minimum
of M/2 children or any number from 2 to the maximum.
 Each node has fewer keys than children will a maximum
of M – 1 keys.
 Keys are arranged in a defined order within the node. All
keys in the sub-tree to the left of a key are predecessors of
the key and those on the right are successors of the key.
 When a new key is to be inserted into a full node is split
into two nodes and the key with the median value is
inserted in the parent node is the root, a new root is
created.
 All levels are on the same level i.e.: there is no empty
sub-tree above the level of the leaves.
Decision Trees:
 Decision tree is a binary tree, where a node
represents some decision and edges emanating
from a node represent the outcome of the decision.
 External nodes represent the ultimate decisions. In
fact all the internal nodes represent the local
decision, if condition is true, then decision 1, else
decision 2 towards a global decision.
 E.g.: A > B ?
B > C ?A > C ?
CBCA
T
TT
F
F F
Greatest among A, B, C
A < B ?
B < C ?B < C ?
A < C ?A< B< C A < C ?
A< C < B B<C<AB<A<CC< A< B
C< B< A
T F
T
T
T
T
F
F
F
F
Ascending order among A, B, C
B+-Tree:
 A B+-Tree is an n-ary tree with a variable but often
large number of children per node. A B+-Tree
consists of a root, internal nodes and leaves. The
root may be either a leaf or a node with two or
more children.
 A B+-Tree can be viewed as a B-Tree in which
each node contains only keys and to which an
additional level is added at the bottom with linked
leaves.
 The primary value of a B+-Tree is in storing data
for efficient retrieval in block oriented storage
context. E.g.: File Systems.
Symbol Table Construction:
 An important part of any compiler, assembler and
loader is the construction and maintenance of a
dictionary containing names and their associated
values. Such a dictionary is also called a symbol
table.
 In a typical compiler, there may be several symbol
tables corresponding to variable, names, labels,
literals etc.
 There are number of phases associated with the
construction of symbol tables. The building phase
involves the insertion of symbols and their
associated values, if known into a table.
 The referencing phase involves the fetching or
accessing of values from a table.
 A binary tree structure is chosen for two reasons that
is:
 a) symbol entries are uniformly distributed according to
alphabetical order.
 b) A binary tree is easily maintained using a few
pointers.
 There are some rules to construct symbol table.
 Allows variable length character strings
 Create trees for variables which are local to a block of
program code. This implies that an attempt to insert a
duplicate entry is an error. Duplicate entries are
permitted as long as they are at different block levels
 The symbol table is a set of tree – one for each block
level.
Graph:
 Graph is a non-linear non-primitive data
structure, which is used to represent relationship
between pairs of elements which are not
necessarily hierarchical in nature.
 A graph is defined as Graph ‘G’ is an ordered set
of vertices or nodes and edges (V, E) which
connect themselves, where V(G) represents the
set of elements called vertices and E(G)
represents the edges between these vertices.
Types of Graph:
 Undirected Graph: In undirected graph, there
is no specific direction associated with the
edges.
 In general, in an undirected graph an edge is
represented by an unordered pair[u, v] and that
can be traverse from ‘u’ toward ‘v’ and vice
versa
 It is a graph such that G = {V, E}, where ‘V’ is
set of vertices and ‘E’ is the set of unordered
pair of vertices.
Example:
 Here V = {v1, v2, v3, v4} and
E = { e1, e2, e3, e4, e5, e6}
i.e.: {(v1, v2), (v2, v3), (v3, v4), (v4, v1), (v1, v3), (v2, v4)}
v1 v2
v4 v3
e4 e2
e1
e3
e6
e5
 Directed Graph: In Directed Graph, an edge is
represented by an ordered pair (u, v) and that can
be traversed only from ‘u’ to ‘v’.
 It is a graph, such that G = {V, E}, where ‘V’ is set
of vertices and ‘E’ is the set of ordered pair of
vertices.
 If an ordered pair (vi, vj) is in set ‘E’, then there is
an edge directed from vi to vj (indicated by arrow
sign).
 In case of undirected graph a pair (vi, vj) in set ‘E’
is unordered. i.e. (vi, vj) and (vj, vi) are the same
edges, but in directed graph they refer to two
different edges.
Example:
 E.g.: Here V = {v1, v2, v3, v4} and
E = {(v1, v4),(v1, v3),(v4, v2),(v4, v3),(v3, v2),(v2, v1)}
v1 v2
v4 v3
Graph Terminology:
 Adjacent Vertices: In case of directed
graph, the vertex vi is adjacent to
another vertex vj, if there is an edge
from vi to vj.
 In the figure or graph, given below v1
is adjacent to v2 and v4. v4 is adjacent
to v2 and v3, v2 is adjacent to v3 but not
adjacent to v1.
 As an edge ‘E’ is represented by pair
of vertices denoted by [u, v], where
vertices ‘u’ and ‘v’ are called end
points of ‘e’. These vertices are also
called adjacent vertices or neighbors.
v1 v2
v4 v3
 Degree of a node/vertex: For an undirected
graph, the degree of vertex ‘vi’ or ‘u’ is the no. of
edges connected with it.
 For a directed graph, there are two types of
degrees. That are in-degree and out-degree.
 In-degree: In-degree of a vertex ‘vi’ is number of edges
incident into ‘vi’. (i.e.: number of edges ending at vi).
 Out-degree: Out-degree of a vertex ‘vi’ is number of
edges emanating from ‘vi’. (i.e.: number of edges
beginning at vi).
 E.g.:
v1 v2
v4 v3
In this undirected graph, node
‘v1’ has degree 3, ‘v2’ has
degree 2, ‘v3’ has degree 3 and
‘v4’ has degree 2.
 In this directed graph, in-degree of
v1= 1 and out-degree of v1 = 2. So,
degree of v1 = in-degree + out-
degree = 1 + 2 = 3.
 Similarly, in-degree of v2 = 1 and
out-degree of v2 = 2. So degree of
v2 = in-degree + out-degree = 1 + 2
=3
 In-degree of v3 = 2, out-degree of
v3 =1. So, degree of v3 = in-degree
+ out-degree = 2 + 1 = 3
 In-degree of v4 = 2, out-degree of
v4 = 1. so, degree of v4 = in-degree
+ out-degree = 2 + 1 = 3
v1 v2
v4 v3
 Source: A vertex ‘u’ is called a source, if it has a
out-degree > 0 and in-degree = 0.
Here,v1 = source, out-degree = 3 > 0 and
in-degree = 0..
 Sink: A vertex ‘u’ is called as sink, if it has in-
degree > 0 but out-degree = 0.
Here,v1 = sink, in-degree = 3 > 0 and
out-degree = 0.
v1
v4v3v2
v1
v4v3v2
 Isolated Vertex: A vertex is isolated if there is no
edge, connected from any vertex to that vertex.
i.e.: if a node ‘u’ has degree = 0, then that node ‘u’
is called isolated vertex. Here ‘V5’ is an isolated
vertex.
 Cycle: If there is a path containing edges which
start from vertex ‘vi’ and ends at vertex vi, then
the path is called cycle.
V1
V3
V4
V2
V5
 Cyclic Graph: A graph with one or more cycles is
known as cyclic graph.
 Acyclic Graph: A graph which does not have
cycles or cyclic paths, then it is called Acyclic
graph. A tree is a acyclic graph.
V1
V3
V4
V2
Here, V1→ V2 → V3 → V1 is a cycle
and V4→ V1 → V2 → V3 → V4 is
another cycle
V1
V3
V4
V2
This two figures
have no cycles.
So, these are
Acyclic Graph
V1
V2
V3
V5V4
 Self Loop: If there is an edge exist, where starting
and end vertex are same. i.e. (vi, vi) is an edge,
then it is called a self loop.
 Parallel/Multiple Edges: In a graph, if there are
more than one edge between the same pair of
vertices then they are known as the parallel or
multiple edges.
V1
V3
V4
V2
Here, V2 contains a self loop.
Here, parallel or multiple edges
exist for the pair of vertices V1, V4.
V1
V3
V4
V2
 Path: A path ‘P’ of length ‘n’, from a vertex ‘u’
to vertex ‘v’ is defined as sequence of ‘n + 1’
vertices. i.e.: P = {v1, v2, … , vn +1}, such that u =
v1 and v = vn + 1
 The path is said to be closed if the end points of
the path are same. i.e. v1 = vn + 1
 The path is said to be simple if all the vertices in
the sequence are distinct with the exception that
v1 = vn + 1, in that case it is known as closed
simple path or loop.
 Simple Graph: A graph which does not have
parallel edges and self loops, is called simple
graph.
 Multi Graph: A graph which contains either a
self loop or parallel or multiple edges or both is
referred as Multi Graph.
 Pendant Vertex: A vertex vi is called pendant
vertex, if in-degree of vi is 1 and out-degree of vi
is 0. V1
V2
V3
V5V4
Here, Pendant Vertices are:
V3, V4, V5 contains a self
loop.
V1
V3
V4
V2
 Weighted Graph: A graph is termed as weighted
if all the edges are labeled with some weights. A
weighted graph can be either directed/undirected.
 Complete Graph: A graph ‘G’ is said to be
complete if there is a path from each vertex to all
other vertices of the graph.
v1 v2
v4 v3
v1 v2
v4 v3
9
8
53
9
8
53
v3
v1 v2
v4 v3 v1 v2
v4
 Connected Graph: A graph is called connected,
if there exist a path from any vertex to any other
vertex or for every pair of distinct vertices vi, vj
in graph G, there exist a path, then it is
connected graph.
 A directed graph with this property is called
strongly connected, otherwise it is called weakly
connected.
V1
V3
V4
V2
V1
V3
V4
V2
Strongly
connected
weakly connected
Representation of Graph:
 The graph can be represented using:
 Sequential/Matrix Representation
 Linked List Representation
 Sequential/Matrix Representation of graph can be
of two types.
 Adjacency Matrix
 Incidence Matrix
Adjacency Matrix:
 For representing a graph ‘G’, with ‘N’ number of
vertices, a matrix of order N x N size can be
considered.
v1 v2
v4 v3
Here, if ‘i’ represents row position and
‘j’ represents column position, then if
there is an edge from vi to vj, then
A[i][j] = 1, else A[i][j] = 0
v1
v2
v3
v4
v1 v2 v3 v4
0 1 0 1
0 0 0 0
1 1 1 0
0 1 0 0
It is a simple way to represent a
graph in the form of matrix, and
the matrix is called Adjacency
matrix.
Disadvantages of Adjacency
Matrix:
 It requires n2 space to represent a graph and also
takes n2 time to solve most of the graph related
problems.
 It may be difficult to insert and delete nodes,
because the size of matrix need to be changed and
at the same time the sequence of the nodes should
be recorded and nodes may be needed to
reordered.
Incidence Matrix:
 In incidence matrix consists of a row for every
vertex and column for every edge.
v1 v2
v4 v3
Here, if there is an edge ‘Ek’ exist from
Vi to Vj , then Vi Ek = 1 and Vj Ek = -1
and others at Ek = 0. So, here for the
edge Ek , Vi , Vj are adjacent nodes.
v1
v2
v3
v4
e1 e2 e3 e4
1 0 0 -1
-1 -1 0 0
0 1 -1 0
0 0 1 1
e1
e2
e3
e4
e5
-1
0
1
0
Linked List Representation:
 While representing a graph in linked list format
the structure of the node will be as follows.
 Here, every vertex consists of 3 parts. That is:
 Next: Pointer to the next vertex in the graph.
 Vertex: Consists of vertex name.
 List: Points to the 1st node of adjacency list of a vertex.
 In case of directed graph, it points to the
successor nodes or adjacency nodes connected
with out-degree edges.
Next Vertex List
Example:
 The adjacency list for the graph is:
 The list representation contains node lists and
edges list given as follows:
A D
E
B C
Node Adjacency List
A B, C, D
B C
C -
D C, E
E C
B
A
EDGE LIST
C
D
E
X
X
X
X
NODE LISTSTART
Graph Traversal:
 A graph can be traversed in two standard ways.
That are:
 Depth First Search(DFS) and
 Breadth First Search(BFS)
 Depth First Search(DFS): It is a type of graph
traversal where we use the concept of stack
simply stack.
 Breadth First Search(BFS): It is a graph
traversal method, which is use the concept of
Queue and it is similar to level by level
examination of an ordered tree.
Depth First Search(DFS) Algorithm:
 During the execution of this traversal, we
consider 3 states. That is:
 Flag = 1, represents Ready State
 Flag = 2, represents Waiting State
 Flag = 3, represents Processed State
 The algorithm for this is:
 [Assume Graph ‘G’ with nodes. This algorithm
will traverse in DFS order by using a stack].
 Step 1: [Initialize all nodes to ready state]
Set Flag = 1 for all the nodes
 Step 2: [Consider a node as 1st node and push into
stack]
PUSH(1)
 Step 3: [Change the status of node 1 to waiting
state]
Set Flag = 2 for node 1
 Step 4: Repeat while stack is not empty
Step 4.1: Set X = POP()
Step 4.2: Process X
Step 4.3: [Change status of X into Processed State]
Set Flag = 3 for node X
Step 4.4: Repeat for all adjacent nodes of X, say Y
Step 4.4.1: if Flag = 1, for node Y, then PUSH(Y)
Set Flag = 2 for node Y
[End of if – Step 4.4.1]
[End of for – Step 4.4]
 Step 5: Exit
Example:1
 The adjacency list for the graph is:
 Flag = 1, Ready state: (A, B, C, D, E)
 Ready State(B, C, D, E): Flag 1
Waiting State(A): Flag 2
Stack(A)
A D
E
B C
Node Adjacency List
A B, C, D
B C
C -
D C, E
E C
A
 Ready State(E): Flag 1
Waiting State(B, C, D): Flag 2
Processed State(A): Flag 3
Stack(B, C, D)
 Ready State()
Waiting State(B,C,E): Flag 2
Processed State(A, D): Flag 3
Stack(B, C, E)
 Ready State()
Waiting State(B, C)
Processed State(A, D, E)
Stack(B, C)
C
D
B
C
E
B
C
B
 Ready State()
Waiting State(B)
Processed State(A, D, E, C)
Stack(B)
 Ready State()
Waiting State()
Processed State(A, D, E, C, B)
Stack(Empty)
 So, sequence of vertex in above graph for DFS:
A, D, E, C, B.
B
Example:2
 Traverse the graph given below in DFS order
beginning with node ‘i’. The adjacency list for the
graph is:
 Flag = 1, Ready state: (A, B, C, D, E, F, G, I, J)
Node Adjacency List
A B, D, C
B E
C G, D
D B
E D
F E, D, I
G D, F
I E, J
J F, G
a
b d c
e f g
i j
 Ready State(A, B, C, D, E, F, G, J): Flag 1
Waiting State(I): Flag 2
Processed State()
Stack(I)
 Ready State(A, B, C, D, F, G): Flag 1
Waiting State(E, J): Flag 2
Processed State(I): Flag 3
Stack(E, J)
 Ready State(A, B, C, D): Flag 1
Waiting State(E, F, G): Flag 2
Processed State(I, J): Flag 3
Stack(E, F, G)
J
E
I
F
G
E
 Ready State(A, B, C): Flag 1
Waiting State(E, F, D): Flag 2
Processed State(I, J, G): Flag 3
Stack(E, F, D)
 Ready State(A, C): Flag 1
Waiting State(E, F, B): Flag 2
Processed State(I, J, G, D): Flag 3
Stack(E, F, B)
 Ready State(A, C): Flag 1
Waiting State(E, F): Flag 2
Processed State(I, J, G, D, B): Flag 3
Stack(E, F)
F
B
E
F
D
E
F
E
 Ready State(A, C): Flag 1
Waiting State(E): Flag 2
Processed State(I, J, G, D, B, F): Flag 3
Stack(E)
 Ready State(A, C): Flag 1
Waiting State()
Processed State(I, J, G, D, B, F, E): Flag 3
Stack(Empty)
 So, the processes nodes in DFS, starting from
node ‘i’ is as follows: I, J, G, D, B, F, E.
 NOTE: There are certain nodes which can not be
traversed as there exist no path from node ‘i’,
which are present in Ready State i.e.: A, C
E
Breadth First Search(BFS) Algorithm:
 During the execution of this traversal, we
consider 3 states. That is:
 Flag = 1, represents Ready State
 Flag = 2, represents Waiting State
 Flag = 3, represents Processed State
 The algorithm for this is:
 [Assume Graph ‘G’ with ‘n’ nodes. This
algorithm will traverse the graph in breadth first
order by using a queue].
 Step 1: [Initialize all nodes to ready state]
Set Flag = 1 for all the nodes
 Step 2: [Consider a node as 1st node and insert
into queue]
Insert(1)
 Step 3: [Change the status of node 1 to waiting state]
Set Flag = 2 for node 1
 Step 4: Repeat while queue is not empty
Step 4.1: Set X = Delete()
Step 4.2: Process X
Step 4.3: [Change status of X into Processed State]
Set Flag = 3 for node X
Step 4.4: Repeat for all adjacent nodes of Y of X
Step 4.4.1: if Flag = 1, for node Y, then Insert(Y)
Set Flag = 2 for node Y
[End of if – Step 4.4.1]
[End of for – Step 4.4]
[End of for – Step 4]
 Step 5: Exit
Example:
 The adjacency list for the graph is:
 Flag = 1, Ready state: (A, B, C, D, E)
 Ready State(B, C, D, E): Flag 1
Waiting State(A): Flag 2
Queue(A)
A D
E
B C
Node Adjacency List
A B, C, D
B C
C -
D C, E
E C
0 1 2 3 4
F = R = -1
A
0 1 2 3 4
F = R = 0
 Ready State(E): Flag 1
Waiting State(B, C, D): Flag 2
Processed State(A): Flag 3
Queue(B, C, D)
 Ready State(E)
Waiting State(C, D): Flag 2
Processed State(A, B): Flag 3
Queue(C, D)
 Ready State(E)
Waiting State(D)
Processed State(A, B, C)
Queue(D)
B C D
0 1 2 3 4
F = 1, R = 3
C D
0 1 2 3 4
F = 2, R = 3
D
0 1 2 3 4
F = 3, R = 3
 Ready State()
Waiting State(E)
Processed State(A, B, C, D)
Queue(E)
 Ready State()
Waiting State()
Processed State(A, B, C, D, E)
Queue(Empty)
 So, sequence of vertex in above graph for DFS:
A, B, C, D, E.
E
0 1 2 3 4
F = 4, R = 4
0 1 2 3 4
F = -1, R = -1
Example:2
 Find the BFS order of the graph as shown in
given figure starting from node a to j . The
adjacency list for the graph is:
Node Adjacency List
A B, D, C
B E
C G, D
D B
E D
F E, D, I
G D, F
I E, J
J F, G
a
b d c
e f g
i j
 Flag = 1, Ready state: (A, B, C, D, E, F, G, I, J)
 Ready State(B, C, D, E, F, G, I, J): Flag 1
Waiting State(A): Flag 2
Processed State()
Queue(A)
 Ready State(E, F, G, I, J): Flag 1
Waiting State(B, D, C): Flag 2
Processed State(A): Flag 3
Queue(B, D, C)
A
0 1 2 3 4 5 6 7
Front = 0, Rear = 0
0 1 2 3 4 5 6 7
Front = -1, Rear = -1
 Ready State(F, G, I, J): Flag 1
Waiting State(D,C,E): Flag 2
Processed State(A, B): Flag 3
Queue(D, C, E)
 Ready State(F, G, I, J): Flag 1
Waiting State(C, E): Flag 2
Processed State(A, B, D): Flag 3
Queue(C, E)
D C E
0 1 2 3 4 5 6 7
Front = 2, Rear = 4
B D C
0 1 2 3 4 5 6 7
Front = 1, Rear = 3
 Ready State(F, I, J): Flag 1
Waiting State(E, G): Flag 2
Processed State(A, B, D, C): Flag 3
Queue(E, G)
 Ready State(F, I, J): Flag 1
Waiting State(G): Flag 2
Processed State(A, B, D, C, E): Flag 3
Queue(G)
E G
0 1 2 3 4 5 6 7
Front = 4, Rear = 5
C E
0 1 2 3 4 5 6 7
Front = 3, Rear = 4
 Ready State(I, J): Flag 1
Waiting State(F): Flag 2
Processed State(A, B, D, C, E, G): Flag 3
Queue(F)
 Ready State(J): Flag 1
Waiting State(I): Flag 2
Processed State(A, B, D, C, E, G, F): Flag 3
Queue(I)
F
0 1 2 3 4 5 6 7
Front = 6, Rear = 6
G
0 1 2 3 4 5 6 7
Front = 5, Rear = 5
 As we reached our destination node ‘I’, we now
backtrack from ‘I’ by going backward direction
of processed state, we get our path our shown
below: I ← F ← G ← C ← A
I
0 1 2 3 4 5 6 7
Front = 7, Rear = 7
Topological Sorting:
 For performing the tasks serially, an acyclic
directed graph can be represented in linear order
of nodes, which is called topological sorting.
 So, if the graph is finite directed graph without
cycles, there exist a topological sort.
A
G
F
B
D
CE
Adjacency Lists
A C
B D, F
C -
D C
E C
F -
G A, F
Algorithm:
 [Consider a graph ‘G’ without cycles, this algorithm finds
the topological order of graph ‘G’].
 Step 1: Find the in-degree(n) of each node ‘n’ of graph
‘G’.
 Step 2: Insert all the nodes with ‘0’ in-degree into Queue.
 Step 3: Repeat until Queue is empty.
Step 3.1: Remove the front node ‘n’ of the Queue.
Step 3.2: Repeat for each neighbor ‘m’ of node ‘n’.
Step 3.2.1: Set in-degree(m) = 0, then in-degree(m) – 1.
Step 3.2.2: If in-degree(m) = 0, then insert it at rear end of
Queue
[End of for – Step 3.2]
[End of loop – Step 3]
 Step 4: Exit
 Here, in the given figure, in-degree of A = 1, in-
degree of C = 3, in-degree of F = 2, in-degree of D
= 1, in-degree of B = 0, in-degree of E = 0 and in-
degree of G = 0.
 The nodes having zero in-degrees are putting in a
Queue. i.e.
 Remove ‘B’ and adding its vertex ‘D’ and ‘F’. ‘D’
having in-degree = 1 and ‘F’ having in-degree = 2.
So, in-deg(D) = 1-1 = 0 and in-deg(F) = 2 – 1 = 1.
B E GQ
0 1 652 3 4
F = 0, R = 2
7
E G DQ
0 1 652 3 4
F = 1, R = 3
7
 Remove ‘E’ and adding its vertex ‘C’. ‘C’ having
in-degree = 3. So, in-deg(C) = 3-1 = 2.
 Removing ‘G’ and adding ‘A’ and ‘F’.
So in-deg(A) = 1 -1 = 0 and in-deg(F) = 1 - 1 = 0.
 Removing ‘D’ and adding ‘C’.
So, in-deg(C) = 2 -1 = 1
G DQ
0 1 652 3 4
F = 2, R = 3
7
D A FQ
0 1 652 3 4
F = 3, R = 5
7
A FQ
0 1 652 3 4
F = 4, R = 5
7
 Removing ‘A’ and adding ‘C’.
So, in-deg(C) = 1 -1 = 1.
 Removing ‘F’.
 Removing ‘C’.
 Finally, the Topological Sorting order is:
B, E, G, D, A, F, C
CQ
0 1 652 3 4
F = 6, R = 6
7
F CQ
0 1 652 3 4
F = 5, R = 6
7
Q
0 1 652 3 4
F = -1, R = -1 and Q is empty
7
Path Matrix or Reachability Matrix:
 A path matrix contains information about each vertex
to other vertex, there exist a path or not.
The adjacency matrix for the graph is:v1 v2
v4 v3
v1
v2
v3
v4
v1 v2 v3 v4
0 1 0 1
0 0 1 1
1 0 0 1
1 0 0 0
A =
From Adjacency Matrix, we
can know, there exist a direct
single edge from one node to
another or not.
 Now consider A2, A3, A4 according to the size of
matrix or number of vertices.
 Here, A2 represent how many paths exist for a
particular node to another node, using two edges
v1
v2
v3
v4
v1 v2
v3 v4
1 1 0 1
2 0 1 1
1 0 0 1
0 0 0 0
A2 =
v1
v2
v3
v4
v1
v1v4v1
-
v2v4v1
v2v3v1
v3v4v1
v2
-
v3v1v2
v4v1v2
-
v3
v1v2v3
-
-
-
v4
v1v2v4
v2v3v4
v3v1v4
v4v1v4
 In A2 matrix, v2 to v1 is having two paths using
two edges. That is: v2v4v1 and v2v3v1
 Here, A3 shows number of paths exist using 3
edges.
v1
v2
v3
v4
v1 v2
v3 v4
2 1 0 1
1 2 0 1
0 1 1 1
0 0 1 1
A3 =
v1v2v4v1
v1v2v3v1
v2v3v4v1
---
v1v4v1v2
v2v4v1v2
v2v3v1v2
v3v4v1v2
v3v1v2v3
v4v1v2v3--- ---
v1
v2
v3
v4
v1 v2 v3
v4
v1v2v3v4
v2v4v1v4
v3v1v2v4
v4v1v2v4
---
---
 Here, A4 shows number of paths exist using 3
edges.
 BN = A + A2 + A3 + …. + AN, where N = total
number of nodes.
v1
v2
v3
v4
v1 v2 v3 v4
1 0 1 1
0 1 1 1
0 1 1 1
0 1 0 1
A4 =
v1v2v3v4v1
---
---
v1
v2
v3
v4
v1 v2 v3
v4
v1v4v1v2v3
---
v1v2v3v1v4
---
v2v3v4v1v2
v3v1v4v1v2
v4v1v4v1v2
v2v4v1v2v3
v3v4v1v2v3
---
v2v3v1v2v4
v3v1v2v3v4
v4v1v2v3v4
 So B4 = A + A2 + A3 + A4
 Now, by representing all non-zero entries by 1, we
obtain path matrix:
v1
v2
v3
v4
v1 v2 v3 v4
4 2 2 4
3 3 2 4
2 3 2 4
1 2 1 3
B =
v1
v2
v3
v4
v1 v2 v3 v4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
P =
So, here P is the path matrix that
shows whether there exist a path from
one node to other or not. vertices
The above matrix shows that there exist a path between any pair
of vertices of given graph. If any zeros are present in path matrix,
then it suggests that no path exist for those pair of vertices
Shortest Path Problems:
 The problem in a graph is about finding a path
between two vertices in such a way that this path
will satisfy some conditions.
 In a non-weighted graph, to find a shortest path,
we count the number of edges. In a weighted
graph, the shortest path is determined by sum of
the weights on edges in a path.
 The different types of algorithm used for this
problem is:
 Warshall’s Algorithm
 Floyd’s Algorithm
 Dijkstra’s Algorithm
Warshall’s Algorithm:
 It is basically used to find the path matrix for a
given graph.
 By using this, one can specify whether there
exists a path between two vertices or not.
 Assume a directed graph ‘G’ with ‘N’ nodes is
maintained in memory by its adjacency matrix
‘A’.
 This algorithm finds path matrix ‘P’ of graph ‘G’.
Algorithm:
 Assume ‘A’ is an adjacency matrix of order N x N
order. This algorithm find the path matrix ‘P’.
Step 1: Let I, J, K
Step 2: Repeat for I = 1 to N incrementing by 1
Step 2.1: Repeat for J = 1 to N incrementing by 1
Step 2.1.1: if A[I][J] = 0, then set P[I][J] = 0
Step 2.1.2: else set P[I][J] = 1
[End of if]
[End of for]
[End of for]
Step 3: Repeat for K = 1 to N incrementing by 1
Step 3.1: Repeat for I = 1 to N incrementing by 1
Step 3.1.1: Repeat for J = 1 to N incrementing by 1
P[I][J] = P[I][J] U (P[I][K] ∩ P[K][J])
[End of for]
[End of for]
[End of for]
Step 4: Exit
All Pair Shortest Path: Floyd’s
Algorithm:
 By using Warshall’s algorithm, one can find path
matrix which shows presence or absence of path
between a pair of vertices.
 If a weighted graph exists and we are interested to
find the length of shortest path between any pair
of vertices, then we follow Floyd’s algorithm for
this purpose.
Algorithm:
 Assume ‘W’ is a matrix of N x N order that
represents a weighted graph. This finds a matrix
‘Q’ of N x N order which represents the shortest
path from any vertex to any vertex.
Step 1: Let I, J, K
Step 2: Repeat for I = 1 to N incrementing by 1
Step 2.1: Repeat for J = 1 to N incrementing by 1
Step 2.1.1: if W[I][J] = 0, then set Q0[I][J] = ∞
Step 2.1.2: else set Q[I][J] = W[I][J]
[End of if]
[End of for]
[End of for]
Step 3: Repeat for K = 1 to N incrementing by 1
Step 3.1: Repeat for I = 1 to N incrementing by 1
Step 3.1.1: Repeat for J = 1 to N incrementing by 1
Set QK[I][J]= MIN(QK-1[I][J], QK-1[I][K] + QK-1[K][J])
[End of for]
[End of for]
[End of for]
Step 4: Exit
Example:
 Consider a directed graph as shown in given figure.
 The corresponding weighted matrix is:
A D
B C
6
8
7
5
4
3
2
A
B
C
D
A B C D
8 6 0 0
7 0 0 3
0 4 0 0
5 0 2 0
W =
In step 2, we store the details of
weighted matrix into ‘Q’. Using
this algorithm, we obtain Q0, Q1,
Q2, Q3 and Q4, where K = 0 to 4
 ‘Q0’ represents the minimum weight between each
pair of nodes using single edge. i.e.:
 ‘Q1’ represents minimum weight in between each
weight at ‘Q0’ and each weight obtained using
intermediate vertex ‘A’.
A
B
C
D
A B C D
8 6 ∞ ∞
7 ∞ ∞ 3
∞ 4 ∞ ∞
5 ∞ 2 ∞
Q0 = =>
A
B
C
D
A B C D
AA AB -- --
BA -- -- BD
-- CB
DA DC--
--
--
--
A
B
C
D
A B C D
8 6 ∞ ∞
7 13 ∞ 3
∞ 4 ∞ ∞
5 11 2 ∞
Q1 = =>
A
B
C
D
A B C D
AA AB -- --
BA BAB -- BD
-- CB
DA DCDAB
--
--
--
 E.g. at Q0, B-B using single edge is ∞. So, now
BAB using two edges, it is 13. So, minimum
distance is B, updated at Q1.
 ‘Q2’ represents minimum weight in between each
weight at ‘Q1’ and each weight obtained using
intermediate vertex ‘B’. E.g. At, Q1, C-D is ∞, and
now CBD is 7. So, minimum distance ‘7’ is
updated at Q2.
A
B
C
D
A B C D
8 6 ∞ 9
7 13 ∞ 3
11 4 ∞ 7
5 11 2 14
Q2 = =>
A
B
C
D
A B C D
AA AB --
BA BAB -- BD
CB
DA DCDAB
CBD--
ABD
CBA
DABD
 ‘Q3’ represents minimum weight in between each
weight at ‘Q2’ and each weight obtained using
intermediate vertex ‘C’. E.g. At, Q2, D-B is 11,
and now DCB is 6. So, minimum distance ‘6’ is
updated at Q3.
 ‘Q4’ represents minimum weight in between each
weight at ‘Q3’ and each weight obtained using
intermediate vertex ‘D’. E.g. At, Q3, BAB is 13,
and now BDC is 9. So, minimum distance ‘9’ is
updated at Q4.
A
B
C
D
A B C D
8 6 ∞ 9
7 13 ∞ 3
11 4 ∞ 7
5 6 2 9
Q3 = =>
A
B
C
D
A B C D
AA AB --
BA BAB -- BD
CB
DA DCDCB
CBD--
ABD
CBA
DCBD
 Finally, we get possible shortest path between
every pair of vertices. i.e. at Q4. In the above
algorithm, we obtain these at matrix ‘Q’.
A
B
C
D
A B C D
8 6 11 9
7 9 5 3
11 4 9 7
5 6 2 9
Q4 = =>
A
B
C
D
A B C D
AA AB
BA BDCB BDC BD
CB
DA DCDCB
CBDCBDC
ABD
CBA
DCBD
ABDC
Dijkstra’s Algorithm:
 Dijkstra’s algorithm is an algorithm for solving
the singe source shortest path problem in a
weighted graph.
 Here we consider a distinct vertex as source and
the algorithm will find the shortest possible path
from source to all other vertices of the graph.
 So, this algorithm is called single source shortest
path algorithm.
Algorithm:
 Step 1:V = {1, 2, 3, 4, 5, 6}
 Step 2: S = {1}
 Step 3: Repeat for i = 2 to N incrementing by 1
D[i] = C(1, i)
[End of for]
 Step 4: Repeat for I = 1 to N - 1 incrementing by 1
 Step 4.1: Choose a vertex w in {V – S}, such that D[w]
is minimum.
 Step 4.2: Add w to S
 Step 4.3: Repeat for each vertex U in {V – S}
D[U] = min(D[U], D[w]+C(w, U))
[End of for]
 Step 5: Exit
Example:
 Consider the graph where source is vertex ‘1’.
 ‘V’ is set of vertices i.e. V = {1, 2, 3, 4, 5, 6}.
 ‘S’ is set of source vertices, initially S = {1}.
 ‘C’ is cost/weight of an edge.
 ‘N’ identifies total number of nodes
 D[N] is an array which contains the distance/weight of
each vertex from source.
 ‘W’ is the vertex with minimum weight in the list of {V
– S}.
 ‘V’ identifies each vertex of {V – S}.
Evolution Process:
V = {1, 2, 3, 4, 5, 6}, S = {1}
D[N] =
 Here, consider vertex 1, at cost ∞. Now, from
vertex 1 to each vertex cost is C(1, i).
1
2
3
4
5
6
90
40
∞ 10 ∞90 70 60
1 2 43 5 6
i
 C(1, 2) => 1 to 2 = 10
C(1, 3) => 1 to 3 = 90
C(1, 4) => 1 to 4 = ∞
C(1, 5) => 1 to 5 = 70
C(1, 6) => 1 to 6 = 60
 When i = 1,
 Step 4:
 Step 4.1: V – S = {2, 3, 4, 5, 6}. Now identify
minimum cost D[w] from 2 to 6 positions. i.e. w = 2
 Step 4.2: Add ‘w’ i.e. 2 to S, So, S = {1, 2}
∞ 10 ∞90 70 60
1 2 43 5 6
i
∞ 10 ∞90 70 60
1 2 43 5 6
U
 Step 4.3: When U = 3,
D[3] = min(D[3], D[2] + C(2, 3))
= min(90, 10 + 20) = min(90, 30).
So, D[3] = 30
 Step 4.4: when i = 2, V = {3, 4, 5, 6}
 Identify minimum cost D[w] from 3 to 6. That is
minimum cost is 30. i.e. w = 3.
 Add w to S = {1, 2, 3}. So V – S = {4, 5, 6}
∞ 10 ∞30 70 60
1 2 43 5 6
 When U = 4,
D[4] = min(D[4], D[3] + C(3, 4))
= min(∞, 30 + 30) = 60.
So, D[4] = 60
 Step 4.5: when i = 3, V = {4, 5, 6}
 Identify minimum cost D[w] from 4 to 6. That is
minimum cost is 60. i.e. w = 4.
 Add w to S, So S = {1, 2, 3, 4}. So V – S = {5, 6}. Now,
 D[U] = min(D[U], D[w] + C(w, U)) i.e.
 D[U] = min(D[5], D[4] + C(4, 5)) = min(70, 60 + ∞) = 70.
So, D[5] = 70.
∞ 10 6030 70 60
1 2 43 5 6
 Step 4.6: when i = 4, V = {5, 6}
 Identify minimum cost D[w] from 5 to 6. That is
minimum cost is 60. i.e. w = 5.
 Add w to S, So S = {1, 2, 3, 4,5}. So V – S = {6}. Now,
 D[6] = min(D[6], D[5] + C(5, 6)) = min(60, 70 + ∞) = 60.
So, D[6] = 60.
∞ 10 6030 70 60
1 2 43 5 6
∞ 10 6030 70 60
1 2 43 5 6
End

Contenu connexe

Tendances

Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)Trupti Agrawal
 
Binary tree and Binary search tree
Binary tree and Binary search treeBinary tree and Binary search tree
Binary tree and Binary search treeMayeesha Samiha
 
Binary search tree in data structures
Binary search tree in  data structuresBinary search tree in  data structures
Binary search tree in data structureschauhankapil
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptSeethaDinesh
 
Unit 5 internal sorting &amp; files
Unit 5  internal sorting &amp; filesUnit 5  internal sorting &amp; files
Unit 5 internal sorting &amp; filesDrkhanchanaR
 
Circular linked list
Circular linked listCircular linked list
Circular linked listchauhankapil
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures treemaamir farooq
 
Key and its different types
Key and its different typesKey and its different types
Key and its different typesUmair Shakir
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary treeZaid Shabbir
 
Types of Tree in Data Structure in C++
Types of Tree in Data Structure in C++Types of Tree in Data Structure in C++
Types of Tree in Data Structure in C++Himanshu Choudhary
 
Types Of Keys in DBMS
Types Of Keys in DBMSTypes Of Keys in DBMS
Types Of Keys in DBMSPadamNepal1
 
DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESAniruddha Paul
 

Tendances (20)

Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Binary tree and Binary search tree
Binary tree and Binary search treeBinary tree and Binary search tree
Binary tree and Binary search tree
 
Binary search tree in data structures
Binary search tree in  data structuresBinary search tree in  data structures
Binary search tree in data structures
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
Unit 5 internal sorting &amp; files
Unit 5  internal sorting &amp; filesUnit 5  internal sorting &amp; files
Unit 5 internal sorting &amp; files
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
 
b+ tree
b+ treeb+ tree
b+ tree
 
Data Structure (Tree)
Data Structure (Tree)Data Structure (Tree)
Data Structure (Tree)
 
Key and its different types
Key and its different typesKey and its different types
Key and its different types
 
Functional dependency
Functional dependencyFunctional dependency
Functional dependency
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
Types of Tree in Data Structure in C++
Types of Tree in Data Structure in C++Types of Tree in Data Structure in C++
Types of Tree in Data Structure in C++
 
Red black tree
Red black treeRed black tree
Red black tree
 
Types Of Keys in DBMS
Types Of Keys in DBMSTypes Of Keys in DBMS
Types Of Keys in DBMS
 
Normalization case
Normalization caseNormalization case
Normalization case
 
Linked List
Linked ListLinked List
Linked List
 
DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTES
 

Similaire à Data structure using c module 2

Similaire à Data structure using c module 2 (20)

Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptx
 
07 trees
07 trees07 trees
07 trees
 
Trees and Graphs in data structures and Algorithms
Trees and Graphs in data structures and AlgorithmsTrees and Graphs in data structures and Algorithms
Trees and Graphs in data structures and Algorithms
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
 
Trees
TreesTrees
Trees
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
Trees in data structures
Trees in data structuresTrees in data structures
Trees in data structures
 
binary tree.pptx
binary tree.pptxbinary tree.pptx
binary tree.pptx
 
358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10
 
Unit 3.ppt
Unit 3.pptUnit 3.ppt
Unit 3.ppt
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
non linear data structure -introduction of tree
non linear data structure -introduction of treenon linear data structure -introduction of tree
non linear data structure -introduction of tree
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Tree terminology and introduction to binary tree
Tree terminology and introduction to binary treeTree terminology and introduction to binary tree
Tree terminology and introduction to binary tree
 
Tree
TreeTree
Tree
 
Data structure tree- advance
Data structure tree- advanceData structure tree- advance
Data structure tree- advance
 
Data structure tree - intermediate
Data structure tree - intermediateData structure tree - intermediate
Data structure tree - intermediate
 
Unit – vi tree
Unit – vi   treeUnit – vi   tree
Unit – vi tree
 

Dernier

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Dernier (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

Data structure using c module 2

  • 1. Data Structure using ‘C’ Module - II Prepared by: Smruti Smaraki Sarangi Asst. Professor School of Computer Application IMS Unison University, Dehradun
  • 2. Contents: TREE  Tree  Tree Terminologies  Binary Tree  Types of Binary Tree  Tree Traversal Methods  Expression Tree  Binary Search Tree  Threaded Binary Tree  Heap Tree  Height Balance or AVL Tree  B-Tree, Decision Tree and B+- Tree  Symbol Table Construction
  • 3. Contents: Graph  Graph  Graph Terminologies  Grap  Expression Tree  Binary Search Tree  Threaded Binary Tree  Heap Tree  Height Balance or AVL Tree  B-Tree, Decision Tree and B+- Tree  Symbol Table Construction
  • 4. Tree:  A tree is a non-linear data structure where items are having hierarchical relationships.  It is a data structure in which each element is attached to one or more elements directly beneath it.  The basic difference between a natural tree and a tree in data structure is that natural tree grows from ground to the air where as tree in data structure grows from top to bottom.
  • 5.  The general tree ‘T’ is a finite non-empty sets whose elements called nodes. One of this element is called root and the remaining elements of any are partitioned into trees which are called the sub- tree of tree ‘T’.  The elements at the highest level of hierarchy is the root. A DCB JIHGFE
  • 6. Tree Terminologies:  Node: Each element of a tree is called a node. It is the basic structure in a tree. There are 10 nodes in the above diagram.  Root: It is specially designated node in a tree, it is the first node in the hierarchical arrangement of data items. Here ‘A’ is the root node.  Parent Node: Parent of a node is the immediate predecessor of a node. E.g.: Here ‘B’ is the parent of ‘E’ and ‘F’.  Child Node: Each immediate successor of a node is referred as child. E.g.: Here, ‘H’, ‘I’, ‘J’ are child nodes of ‘D’
  • 7.  Siblings: The child nodes belong to a single parent are known as siblings. E.g.: Here, ‘E’ and ‘F’ are siblings because they have a single parent ‘B’.  Level of the tree: The root of a tree is at level ‘0’. Its children are at level ‘1’ and the sub-children of the children of the root are at level ‘2’ and so on.  Degree of an element/node: The number of sub- trees of a given node is called the degree of the node or the degree of an element or node is the number of children it has. A terminal node is called leaf node and the degree of a leaf node is ‘0’. E.g.: Here, ‘B’ has degree ‘2’, ‘C’ has degree ‘1’ and ‘F’ has no degree or degree ‘0’.
  • 8.  Degree of a tree: The maximum degree of nodes in a given tree is called the degree of a tree. In above tree, the maximum degree of ‘A’ and ‘D’ is ‘3’. So the degree of the tree is ‘3’.  Terminal Node: A node with degree ‘0’ is called leaf node or terminal node. E.g.: Here, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’ are the leaf nodes.  Edge: It is a connecting line between two nodes. E.g.: ‘BE’ is an edge.  Path: Path is a sequence of consecutive edges from source node to destination node. In above tree, the path between ‘A’ to ‘J’ is given by node pairs (A, D) and (D, J). A path ending in a leaf is called a branch. E.g.: AE, AF, AG, AI, AJ are branches.
  • 9.  Depth of a tree: The depth of Node ‘X’ is the length of unique path from root to Node ‘X’. Thus root is at depth ‘0’. In the above tree, depth of ‘E’ is 2 and depth of ‘B’ is ‘1’.  Height of the tree: The height of Node ‘X’ is the longest path from the Node ‘X’ to the leaf node. So all the leaf nodes are at height ‘0’. In above tree, height of ‘B’ is ‘1’ and height of ‘J’ is ‘0’.  Ancestor and Descendant: If there is a path from node ‘N1’ to ‘N2’ then ‘N1’ is an ancestor of ‘N2’ and ‘N2’ is the descendant of ‘N1’. E.g.: In the above tree ‘A’ is ancestor of ‘G’ and ‘C’ and ‘G’ and ‘C’ are descendant of ‘A’.
  • 10.  Forest: A forest is a set of isolated tree or disjoint tree. A set of trees is called Forest. Here after deleting the root ‘A’, remaining are called Forest. A DCB JIHGFE DCB JIHGFE
  • 11. Note:  Root node does not have parent node.  A node has no children is called leaf node.  A tree having ‘N’ nodes would have N – 1 edges.  There will be exactly one path between the root and any other node in the tree.  The nodes with at least one child are called as non-terminal or internal nodes.  Terminal nodes are called external or leaf nodes.
  • 12. Binary Tree:  A Binary tree ‘T’ is defined as a finite set of elements or data items, called nodes, such that:  ‘T’ is empty, called the null tree or empty tree.  ‘T’ contains a distinguished node ‘R’ called root of the ‘T’, and the remaining nodes of ‘T’ from an ordered pair of disjoint binary trees ‘T1’ and ‘T2’ which are called left sub-tree and the right sub-tree respectively.  The general tree is never empty. The tree can contain any number of children. But binary tree has almost 2 child.
  • 13.  If ‘T1’ is non-empty, then its root is called the left successor of ‘A’. Similarly if ‘T2’ is non-empty, then the root is called the right-successor of ‘A’.  Binary trees ‘T’ and ‘Tꞌ’ are said to be similar, if they have same structure and same set. The trees are said to be copies, if they are similar and if they have the same elements contained at the corresponding A CB HG F ED JI
  • 14.  The tree does not contains a root ‘R’ then two tree ‘T1’ and ‘T2’ are called respectively the left sub- tree and right sub-tree of ‘R’  Here, (1) and (3) are copies and (1) and (4) are similar. A B DC E F HG E F HG A B DC 1 2 3 4
  • 15. Binary Tree Vs Tree: Binary Tree  A binary tree can be empty.  Each element in a binary tree having almost two sub-trees (one or both these sub-trees may be empty.  The sub-trees of each element in a binary tree are ordered. Tree  A tree can not be empty.  Each element in a tree can have any number of sub- trees.  These sub-trees of tree are unordered.
  • 16. Types of Binary Tree:  Strictly Binary Tree: If every non-leaf node in a binary tree has non-empty left and right sub- trees, the tree is termed as a strictly binary tree. A strictly binary tree with ‘n’ leaves always contains 2n – 1 nodes. A CB GFED JI
  • 17.  Full Binary Tree: A Binary tree ‘T’ is called Full, if it is having maximum number of nodes in all its levels. A CB GFED
  • 18.  Complete Binary Tree: Complete Binary tree means that the elements have 2 nodes. The tree ‘T’ is said to be complete if all its levels except possibly nodes and if all the nodes at last level appear as far left as possible.  A binary tree of depth ‘d’ is an almost complete binary tree, if  Each leaf in the tree is either at level ‘d’ or at level ‘d – 1’.  For any node ‘n’, in the tree with a right descendant at level ‘d’, all the left descendants of ‘n’, that are leaves are also at level ‘d’. A CB GFED JI K
  • 19.  Extended Binary Tree: A binary tree ‘T’ is said to be 2-tree or an extended binary tree of each node ‘n’ has either 0 or 2 children. In such a case the node with 2 children are called internal nodes and nodes with zero children are called external nodes. (1) 1 2 3 6 54 (2)
  • 20.  Skew Binary Tree: A tree having only one path which contains h + 1 number of nodes, if ‘h’ is the height. A B D C (1) A B D C (2) E
  • 21. Memory Representation of Binary Tree:  There are two common methods used for representing a binary tree.  Sequential Representation using array  Linked Representation using linked list with pointers. Array Representation of Binary Tree:  An one dimensional array can be used to represent a binary tree in the memory. Here, we consider that root is present at index 0. Assume tree[N] is an array representing binary tree. If ‘i’ be index, then  Root node is stored at index 0. i.e. root is at tree[0].  Left child is stored at tree[2 * i + 1].  Right child is stored at tree[2 * i + 2].
  • 22. Drawbacks of Array Representation :  While representing a binary tree in the form of an array, most of the memory blocks in the middle will be left blank or unused if the tree is not a complete binary tree. 10 3020 605040 9080 0 4 1 2 70 3 5 7 11 12 10 20 30 40 50 60 70 80 90 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 23. Linked Representation of Binary Tree:  A binary tree can be represented by using linked list, where each node is divided into 3 parts as:  Info: it is used to store the information.  Left: it is a pointer that holds the address of left child.  Right: it is a pointer that holds the address of right child.  If any sub-tree of a node is empty, then its corresponding pointer of the node contains NULL, indicating absence of sub-tree. Left Info Right
  • 25. Construction of General Tree to Binary Tree:  It is convenient to represent binary tree than representing general tree in a program, because in case of general tree, the number of edges connected from a node at any given time is unpredictable.  Therefore the node space has to be managed in such a way that each node is allowed a variable number of sub-tree pointers.  In case of binary tree each node has predictable maximum of two sub-tree pointers.
  • 26.  A general tree can be converted into an equivalent binary tree. The conversion process is called the natural correspondence between general and binary trees. The procedure is:  Insert edges connecting siblings from left to right at the same level.  Delete all edges of a parent to its children expect to its left most offspring.  Rotate the resultant tree 45o to mark clearly left and right sub-trees.
  • 27. Example:  Initial transformation of general tree as shown below: A B C D FE HG JI ML K
  • 28.  Binary tree corresponding to general tree is: A B C D FE HG JI ML K A B C D F E H G J I M L K
  • 29. Traversal of Binary Tree:  The process of visiting each node of the tree exactly once is called tree traversal. The traversal of a binary tree involves three basic activities, such as:  Visiting the root.  Traverse the left sub-tree.  Traverse the right sub-tree.  The above tree traversal methods can be implemented in two ways. That are:  Recursive Tree Traversal  Non-Recursive Tree Traversal
  • 30.  The three basic activities are done in different order. There are three types of traversal methods used. That is:  Pre-order traversal (RLTRT)  In-order traversal (LTRRT)  Post-order traversal (LTRTR) Recursive Binary Tree Traversal:
  • 31.  The tree will be traversed in the following order:  Visit the root  Traverse the left sub-tree in pre-order.  Traverse the right sub-tree in pre-order.  The algorithm for this is: Pre-Order(Node) Step 1: if Node != Null, then Step 1.1: Process(Node) Step 1.2: Pre-Order(Left-child[Node]) Step 1.3: Pre-Order(Right-child[Node]) [End of if] Step 2: Exit Pre-Order Traversal (RLTRT):
  • 32.  The tree will be traversed in the following order:  Traverse the left sub-tree in in-order.  Visit the root  Traverse the right sub-tree in in-order.  The algorithm for this is: In-Order(Node) Step 1: if Node != Null, then Step 1.1: In-Order(Left-child[Node]) Step 1.2: Process(Node) Step 1.3: In-Order(Right-child[Node]) [End of if] Step 2: Exit In-Order Traversal (RLTRT):
  • 33.  The tree will be traversed in the following order:  Traverse the left sub-tree in post-order.  Traverse the right sub-tree in post-order.  Visit the root  The algorithm for this is: Post-Order(Node) Step 1: if Node != Null, then Step 1.1: Post-Order(Left-child[Node]) Step 1.2: Post-Order(Right-child[Node]) Step 1.3: Process(Node) [End of if] Step 2: Exit Post-Order Traversal (RLTRT):
  • 34.  The Pre-Order Traversal is: ABDECFG  The In-Order Traversal is: DBEAFCG  The Post-Order Traversal is: DEBFGCA Example: A CB GFED
  • 35. Pre-Order(root)  Step 1: Let PTR = root  Step 2: Repeat while PTR != NULL  Step 2.1: Process INFO[PTR]  Step 2.2: if RIGHT[PTR] != NULL, then PUSH(RIGHT[PTR])  Step 2.3: if LEFT[PTR] != NULL, then PTR = LEFT[PTR]  Step 2.4: else PTR = POP() [End of if] [End of while]  Step 3: Exit Non-Recursive Pre-Order Traversal:
  • 36. In-Order(root)  Step 1: Let PTR = root  Step 2: Repeat while PTR != NULL  Step 2.1: PUSH(PTR)  Step 2.2: PTR = LEFT[PTR] [End of while]  Step 3: Set PTR = POP()  Step 4: Repeat while PTR != NULL  Step 4.1: Process INFO[PTR]  Step 4.2: if RIGHT[PTR] != NULL, then PTR = RIGHT[PTR] GOTO Step 2 [End of if]  Step 4.3: PTR = POP() [End of while]  Step 5: Exit Non-Recursive In-Order Traversal:
  • 37. Post-Order(root)  Step 1: Let PTR = root  Step 2: Repeat while PTR != NULL  Step 2.1: PUSH(PTR)  Step 2.2: if RIGHT[PTR] != NULL, then PUSH(RIGHT[PTR]) [End of if]  Step 2.3: PTR = LEFT[PTR] [End of while]  Step 3: PTR = POP()  Step 4: Repeat while PTR > 0 and PTR != NULL  Step 4.1: Process INFO[PTR]  Step 4.2: PTR = POP() [End of while]  Step 5: if PTR < 0 AND PTR != NULL, then  Step 5.1: Set PTR = - PTR  Step 5.2: GOTO Step 2  Step 6: Exit Non-Recursive Post-Order Traversal:
  • 38. Construction of a Binary Tree:  A binary tree can be constructed by using a combination of tree traversal methods, such as:  Pre-order and In-order Traversal  Post-order and In-order Traversal  Pre-order and Post-order Traversal
  • 39. Construction of a Binary Tree Using Pre-order and In-Order Traversal: Procedure:  Step 1: First node of the Pre-order traversal is the root node of the tree.  Step 2: Find the position of the root node in the in-order traversal.  Nodes proceeding the root in the In-order, construct the left sub-tree.  Nodes succeeding the root in the In-order, construct the right sub-tree.  Step 3: Find out the next roots for each sub-trees using pre- order  Step 4: Continue the above process until leaf nodes are found.
  • 40. Example:  Construct a binary tree from the given pre-order and in-order tree traversal. Pre-order: ABDEHICFG and In-order: DBHEIAFCG. Here, Root = A for the tree. For sub-trees of root A, the node ‘B’, ‘C’ and ‘E’ are the roots. A B C D E F G H I DBHEI FCG HEI
  • 41.  The first node in pre-order traversal is the root node of the tree. Here, ‘A’ is the root.  Find the position of root node ‘A’ in in-order traversal.  The nodes preceding the root node in the in-order traversal are the nodes of the left sub-tree of the root node i.e. DBHEI and the nodes succeed to the root node are the nodes in the right sub-tree of the node FCG.  Now take two sets of in-order and pre-order traversals of the left and right sub-trees of the root.
  • 42.  The first set is the nodes appear precede to the root node in in-order traversal i.e. DBHEI and the combination of those nodes only appear in pre- order traversal just after the root node. i.e. BDHEI.  The second set is the nodes appear in in-order traversal i.e. FCG and the nodes in the pre-order traversal except the root node and the nodes considered in the first set i.e. CFG.  Considering these two sets of pre-order and in- order traversals for the left and right sub-trees we can repeat step - 2 and step - 3 till the entire tree is constructed.
  • 43. Construction of a Binary Tree Using In-order and Post-Order Traversal: Procedure:  Step 1: Here, last node in the Post-order traversal is considered as root node of the tree.  Step 2: Find the position of the root node in the in-order traversal.  Nodes preceding the root in the In-order, construct the left sub-tree.  Nodes succeeding the root in the In-order, construct the right sub-tree.  Step 3: Find out the next roots for each sub-trees using post-order  Step 4: Continue the above process until leaf nodes are found.
  • 44. Example:  Construct a binary tree from the given post-order and in-order tree traversal. Pre-order: DHIEBFGCA and In-order: DBHEIAFCG. Here, Root = A for the tree. For sub-trees of root A, the node ‘B’, ‘C’ and ‘E’ are the roots. A B C D E F G H I DBHEI FCG HEI
  • 45.  The last node in post-order traversal is the root node of the tree. Here, ‘A’ is the root.  Find the position of root node ‘A’ in in-order traversal.  The nodes preceding the root node in the in-order traversal are the nodes of the left sub-tree of the root node i.e. DBHEI and the nodes succeed to the root node are the nodes in the right sub-tree of the node FCG.  Now take two sets of in-order and post-order traversals of the left and right sub-trees of the root.
  • 46.  The first set is the nodes appear preceding to the root node in in-order traversal i.e. DBHEI and the combination of those nodes only appear in post- order traversal just before the root node. i.e. DHIEB.  The second set is the nodes appear after the root node is in-order traversal i.e. FCG and the nodes in the post-order traversal except the root node and the nodes considered in the first set i.e. FGC.  Considering these two sets of post-order and in- order traversals for the left and right sub-trees step - 2 and step – 3 is repeated till the entire tree is constructed.
  • 47. Construction of a Binary Tree Using Pre-order and Post-Order Traversal:  Construct a binary tree from the given pre-order and post-order tree traversal. Pre-order: ABDEHICFG Post-order: DHIEEBFGCA A B C D E F G H I DHEI and DHIE , B = x1 FG, C= x2 HEI
  • 48.  The first node of pre-order traversal and last node of post-order traversal is considered as root of the tree.  Find the node succeeding the root node in pre- order, say x1 and the node preceding the root node in post-order say x2.  If x1 = x2, then it can be taken as left or right child of root and which may not result unique tree  If x1 != x2, then x1 is taken as left child i.e. B, and x2 is taken as right child i.e. C of root node.  Find the position of x2, i.e. ‘C’ in pre-order and position of x1 i.e. ‘B’ in the post-order.  Consider two sets of pre-order and post-order traversal of left and right sub-tree of root.
  • 49.  The first set consists of nodes that are present after x1 and before x2 in pre-order traversal i.e. DEHI and the nodes present before x1 in post-order i.e. DHIE.  The second set consists of nodes that are present after x2 in pre-order traversal i.e. FG and the nodes present after x1 and before x2 in post-order traversal i.e. FG.  By taking 2 sets of pre-order and post-order traversals from left and right sub-trees, repeat steps-2 and 3 to construct the entire tree.
  • 50. Expression Tree:  It is a binary tree, which stores an arithmetic expression. The leaf nodes of the expression tree are always operands and all other internal nodes are the operators, including the root. Divide and conquer technique used to convert an expression into a binary tree.  E.g. (a + b + c) * ((d – e) / (f + g – h)) * + / h g +d e - f - c ba +  Precedence Table: Brackets innermost: Highest level ^ (exponential) : Higher level * and / : Middle level + and - : Lowest level
  • 51. Procedure for constructing an Expression Tree:  Find out the prefix or postfix notation of given infix expression.  Identify the root of the expression tree using prefix (1st symbol) or postfix notation (last symbol).  Identify root in the infix and identify left sub-tree, right sub-tree.  Find the next root nodes of each sub-trees in infix notation.  Continue this process until leaf nodes exist. Note: Here, we will find all the leaf nodes are the operands all the internal nodes are the operators. E.g.: Infix: (A+B*(D – E/F)), Prefix: -+A*B – D / EF
  • 52. Construction of an expression tree from a postfix expression:  Step 1: Scan each symbol from the postfix expression.  Step 2: If an operand is found, then create a one node tree and push a pointer to it onto the stack.  Step 3: If an operator is found, then POP two pointers belonging to two trees say T1 and T2 from stack and construct a tree where root is the operator, T2 is left sub-tree and T1 is right sub-tree respectively.  Step 4: PUSH the pointer to the above resultant sub- tree onto STACK.  Step 5: Exit.
  • 53. [Where an expression ‘E’ in postfix notation appended with ‘)’, a special symbol as delimiter. Assume GETSYMBOL() is a procedure for scanning a symbol from expression ‘E’, GETNODES() is for creating a new node]. Step 1: SYMBOL = GETSYMBOL(E) Step 2: Repeat while SYMBOL != ‘)’ Step 2.1: if SYMBOL = OPERAND, then NEW = GETNODE(NODE) INFO[NEW] = SYMBOL PUSH(NEW) Algorithm:
  • 54. Step 2.2: else Step 2.2.1: if SYMBOL = OPERATOR, then PTR1 = POP() PTR2 = POP() NEW = GETNODE(NODE) INFO[NEW] = SYMBOL LEFT[NEW] = PTR2 RIGHT[NEW] = PTR1 PUSH(NEW) [End of if] [End of if] SYMBOL = GETSYMBOL(E) [End of while] Step 3: Exit
  • 55. Example on Construction of Expression Tree:  Construct an expression tree for the postfix expression: ABC * + DE ^ /  Solution: Given expression is : ABC * + DE ^ /. Now add ‘)’ at the end of the given postfix expression. So, the expression becomes as: ABC*+DE^/).  Scan each symbol from left to right in postfix expression. When the symbol is operand then create a one node tree and push its address into stack. When the symbol is operator, then POP two addresses into pointers T1 and T2 respectively.
  • 56.  Construct a tree where root is the operator, T2 is left sub-tree and T1 is the right sub-tree. Push the root address of the resultant tree into stack.  Scan ‘A’: Scan ‘B’:  Scan ‘C’: A BA A CB
  • 57.  Scan ‘*’: Scan ‘+’:  Scan ‘D’: A * CB + * CB A + * CB A D
  • 58.  Scan ‘*’: Scan ‘^’:  Scan ‘/’:  This the final expression tree. + * CB A D E + * CB A ^ ED / ^ ED + * CB A
  • 59. EVAL_EXP_TREE(ROOT, VAL) Step 1: PTR = ROOT Step 2: if PTR != NULL, then Step 2.1: PTR1 = LEFT[PTR] Step 2.2: PTR2 = RIGHT[PTR] Step 2.3: if INFO[PTR] != OPERATOR, then T1 = INFO[PTR1] Step 2.4: else T1 = EVAL_EXP_TREE(PTR1, VAL) [End of if] Algorithm for Evaluation of Expression Tree:
  • 60. Step 2.5: if INFO[PTR2] != OPERATOR, then T2 = INFO[PTR2] Step 2.6: else T2 = EVAL_EXP_TREE(PTR2, VAL) Step 2.7: OPERATOR = INFO[PTR] Step 2.8: VALUE = T1 OPERATOR T2 Step 2.9: RETURN(VAL) [End of if] Step 3: Exit
  • 61. Binary Search Tree (BST):  A binary tree ‘T’ is termed as binary search tree, if each node ‘n’ of ‘T’ satisfies the following properties.  The value of ‘n’ is greater than the values of all nodes in its left sub-tree and  The value of ‘n’ is less than the values of all nodes in its right sub-tree.  A binary search tree is useful for binary search.
  • 62. Construction of Binary Search Tree:  While constructing a BST, initially, we store the first node as Root node and then we follow insertion of a node based on the rules of BST. So, for each insertion, we need to search for appropriate node either left or right based on the value of the node to be inserted.  E.g.: Construct a BST with the following input values: 70, 20, 11, 45, 95, 76, 29, 59, 99 76 70 9520 11 9945 29 59
  • 63. Algorithm for insertion into BST: Insert_BST(Root, Left, Right, Info, Item, Avail) [Allocates the memory for Fresh node and initialize Info part of the node with Item.] Step 1: Fresh = Avail Step 2: Info[Fresh] = Item Step 3: Left[Fresh] = NULL Step 4: Right[Fresh] = NULL Step 5: if Root = NULL, then Root = Fresh Step 6: else Step 6.1: PTR = Root
  • 64. Step 6.2: Repeat while (PTR != NULL) Step 6.2.1: if (Info[Fresh] < Info[PTR]), then, PREV = PTR PTR = Left[PTR] Step 6.2.2: else PREV = PTR PTR = Right[PTR] [End of if] [End of while] Step 6.3: if (Info[Fresh] < Info[PREV]), then Left[PREV] = Fresh Step 6.4: else Right[PREV] = Fresh [End of if] Step 7: Exit
  • 65. Example:  Using the algorithm , construct a BST, using the following input values: 15, 21, 10, 5, 18, 13, 25, 11. 200 15 300 400 10 500 600 21 700 800 13 XX 5 X X 18 X X 11 X X 25 X Root 100 100 200 600 300 700400 500 800
  • 66. Deletion of Nodes from BST:  While deleting nodes in a BST, the following list comes into out mind. The node to be deleted can be any one of the following types.  Leaf nodes of a tree. (e.g. 20, 37, 65, 85 etc.)  Internal node, which is connected with one child/sub-tree i.e. either right or left. (e.g. 35, 45, 55, 80).  Internal node, which is connected with two child/sub-trees i.e. right and left. (e.g. 30, 90 etc.)  Root of the tree. e.g. 50.
  • 68. Case 1:  When leaf node is deleted e.g. 20 50 40 70 60 55 90 37 9565 9252 80 85 45 423520 30
  • 69. Case 2.1:  When an internal node with right child is deleted e.g. 35 50 40 70 60 55 90 37 9565 9252 80 85 45 423520 30
  • 70. Case 2.2:  When an internal node with right child is deleted e.g. 80 50 40 70 60 55 90 37 9565 9252 80 85 45 423520 30
  • 71. Case 3.1:  When an internal node with left child is deleted e.g. 95 50 40 70 60 55 90 37 9565 9252 80 85 45 423520 30
  • 72. Case 3.2:  When an internal node with right child is deleted e.g. 55 50 40 70 60 55 90 37 9565 9252 80 85 45 423520 30
  • 73. Case 4.1:  When an internal node having left and right sub- trees is deleted e.g. 90 50 40 70 60 55 90 37 9565 9252 80 85 45 423520 30
  • 74. Case 4.2:  When an internal node having left and right sub- trees is deleted e.g. 60 50 40 70 60 55 90 37 9565 9252 80 85 45 423520 30
  • 75. Case 4.3:  When the root node is deleted i.e. 50 50 40 70 60 55 90 37 9565 9252 80 85 45 423520 30 Root
  • 76. Algorithm for Deletion in BST: DEL_BST(Root, Left, Right, Info, Item) [Assume a BST whose root node is identified by a pointer Root, Left and Right identifies the address of left and right nodes. Item is the info of the node to be deleted]  Step 1: if Root = NULL, then Display “Underflow” Return [End of if]  Step 2: PTR = Root
  • 77.  Step 3: Repeat while PTR != NULL and Info[PTR] != Item Step 3.1: if Item < Info[PTR], then PREV = PTR PTR = Left[PTR] Step 3.2: else PREV = PTR PTR = Right[PTR] [End of if] [End of while] //At the end of the Step – 3, either PTR = NULL or Node with Info = Item is found.
  • 78.  Step 4: if PTR = NULL, then Display “Item not found” Return //To delete leaf node  Step 5: elseif(Left[PTR] = NULL AND Right[PTR] = NULL), then Step 5.1: if Item < Info[PREV], then Left[PREV] = NULL Step 5.2: else Right[PREV] = NULL [End of if]
  • 79. //To delete internal node with right child  Step 6: elseif(Left[PTR] = NULL AND Right[PTR] != NULL), then Step 6.1: if Item < Info[PREV], then Left[PREV] = Right[PTR] Step 6.2: else Right[PREV] = Right[PTR] [End of if] //To delete internal node with left child • Step 7: elseif(Right[PTR] = NULL AND Left[PTR] != NULL), then Step 7.1: if Item < Info[PREV], then Left[PREV] = Left[PTR]
  • 80. Step 7.2: else Right[PREV] = Left[PTR] [End of if] //To delete Root node of the tree • Step 8: elseif (PTR = Root), then Step 8.1: if(Left[Root] = NULL AND Right[Root] = NULL), then Root = NULL Step 8.2: else P1 = Right[PTR] Repeat while(Left[P1] != NULL) P1= Left[P1] [End of while] Left[P1] = Left[Root] Root = Right[Root] [End of if]
  • 81. //To delete internal node with two child trees • Step 9: else Step 9.1: P1= Right[PTR] Step 9.2: Repeat while(Left[P1] != NULL) P1 = Left[P1] [End of while] Step 9.3: Left[P1] = Left[PTR] Step 9.4: if (Item < Info[PREV]), then Left[PREV] = Right[PTR] Step 9.5: else Right[PREV] = Right[PTR] [End of if] [End of if – Step – 4] • Step 10: Exit
  • 82. Threaded Binary Tree:  In linked representation of binary tree, the number of NULL links or NULL pointers are actually more than Non-NULL pointers.  Here in given figure, a binary tree consists of 6 nodes, where total NULL pointers are 7 and Actual pointers/Non-NULL pointers are 5.  A binary tree with ‘N’ nodes has: Total Pointers = 2N NULL Pointer = N + 1 Non – NULL Pointers = N - 1
  • 83. 200 15 300 400 10 500 X 21 X 800 13 XX 5 X X 11 X Root 100 100 200 300 400 500 800
  • 84.  A. J. Perlis and C. Thornton jointly proposed an idea to make use of NULL pointers, which will be replaced with special pointers called threads.  A binary tree with such pointers or threads is called threaded binary tree.  The advantages of threaded binary tree is that traversal, insertion and deletion operations can be performed without using either stack or recursion.  The threads in a tree diagram of threaded binary tree are usually indicated by dotted lines.  In a right-in threaded binary tree each right NULL pointers is replaced by special pointers called r- thread, to the in-order successor of that node.
  • 85.  Similarly, in left-in-threaded binary tree each left NULL pointer is replaced by a special pointer called l-thread, to the in-order predecessor of that node.  An in-threaded binary tree may be defined as a binary tree, which is both left-in-threaded and right-in-threaded.  A threaded binary tree is constructed from a binary tree by taking any of the tree-traversal methods. There are two types of threading. That is:  One way Threading  Two way Threading
  • 86. One way Threading:  A threading will appear in left or right field.  The thread is the left field will point to the previous node in the in-order traversal of the tree. This type of traversing is called left-in threading.  The thread which appears in the right field will point to the next node in the in-order traversal, this is the right-in threading.
  • 87. Two way Threading:  In two-way threading, the thread appears in left and right field. The left pointer of the first node and right pointers of the last node will contain NULL entries in their pointers.  A header node is implemented where address is tide by these two pointers and header node always stores the address of the root node.
  • 88. Constructing Threaded Binary Tree using In-Order Traversal: Procedure:  Identify each node having NULL pointers.  Find the position of identified nodes and their adjacent nodes in in-order traversal.  Input the appropriate thread value to point  Point the dangling pointers to header node. E.g. The in-order traversal of binary tree is: DBEAFC A B C FED
  • 89.  Here, according to the Adjacency of the nodes:  Right link of ‘D’ is pointed to ‘B’  Left link of ‘E’ is pointed to ‘B’  Right link of ‘E’ is pointed to ‘A’  Left link of ‘F’ is pointed to ‘A’  Right link of ‘F’ is pointed to ‘C’  Two dangling pointers i.e. left link of ‘D’ and right link of ‘C’ are pointed to header  So, the threaded binary tree for this is given below: A B C FED Header node
  • 90.  The one way in-order threaded binary tree is: Right –in threaded binary tree. A B D E C HG JF L K
  • 91.  The two way in-order threaded binary tree is: A B D E C HG JF L K
  • 92.  The two way threading with header node: A B D E C HG JF L K Header Node
  • 93.  When we represent threaded binary tree in memory, each node structure is added with two logic fields, l-thread and r-thread in order to distinguish between actual pointers and threads. The structure of node looks as follows:  Here, l-thread and r-thread takes the values either 0 or 1.  l-thread = 1, indicates left is a normal pointer  l-thread = 0, indicates left is a thread  r-thread = 1, indicates right is a normal pointer  r-thread = 0, indicates right is a thread. l- thread left info right r-thread
  • 94. 111 1 100 1100 111 100 1 200 1A 300 300 1 600 0C 111 200 1 400 1B 500 500 0 200 1E 100 111 0 111 0D 200 600 0 100 0F 300
  • 95. Advantages of threaded binary tree:  The traversing operation is more faster than that of its unthreaded version, because with threaded binary tree non-recursive implementation is possible which can run faster and does not require the botheration of stack management.  We can efficiently determine the predecessor and successor nodes starting from any node this is more time consuming and default in case of unthreaded binary tree.  Any node can be accessible from any other node. Threads are usually more to upward where as links are downward. Thus, in a thread tree, one can move in either direction and move only in downward direction starting from root.
  • 96. Heap Tree:  A heap is defined as an almost complete binary tree of ‘n’ nodes, such that the value of each node is less than or equal to or greater than or equal to the value of the father or parent node.  A heap tree is defined as an almost complete binary tree of ‘n’ nodes, where path from root node to a terminal node forms an ordered list. There are two types of heap trees. That is: ◦ Max Heap Tree/Descending Heap Tree ◦ Min Heap Tree/Ascending Heap Tree
  • 97. Max Heap Tree/Descending Heap Tree:  Max Heap Tree is the tree, where each parent node contains the largest key value or equal key value to its child nodes .  Here path from root node to a terminal node forms an ordered list of elements arranged in descending order, with root node has largest key value or equal key value to its child. 70 40 15 17 57109 50 20 10
  • 98. Min Heap Tree/Ascending Heap Tree:  Min Heap Tree is the tree, where each parent node contains the smallest key value or equal key value to its child nodes.  Here path from root node to a terminal node forms an ordered list of elements arranged in ascending order, with root node has smallest key value or equal key value to its child. 15 17 50 70 170100150120 20 60 40
  • 99. Notes:  Heap tree is useful in implementing the priority queue, where elements can be inserted arbitrarily but they are arranged in a heap.  So, in ascending heap, elements can be deleted in ascending priority queue order and in descending heap, elements can be deleted in descending priority queue manner.
  • 100. Construction of Heap Tree:  Procedure: Suppose ‘H’ is a heap with ‘N’ nodes and assume Item is the value given and it is to be inserted into heap ‘H’ as follows:  First join Item at the end of ‘H’, so that ‘H’ becomes an almost complete binary tree, but not necessarily a heap.  Find the appropriate place for Item in ‘H’, So that ‘H’ finally becomes a heap.  E.g.: Construct a Max Heap from the following sequence of inputs: 45, 32, 50, 22, 65, 55, 77  Insert 45: Insert 32: Insert 50: 45 3 2 4 5 3 2 4 5 5 0 3 2 5 0 4 5
  • 101.  Insert 22:  Insert 65:  Insert 55: 3 2 5 0 4 5 2 2 3 2 5 0 4 5 2 2 65 6 5 5 0 4 5 2 2 32 5 0 6 5 4 5 2 2 32 5 0 65 4 5 2 2 32 5 5 5 0 65 5 5 2 2 32 4 5
  • 102.  Insert 75:  After inserting all nodes, the construction is finished and the final max heap tree is: 5 0 65 4 52 2 32 5 5 5 0 65 7 72 2 32 4 5 77 55 5 0 77 6 52 2 32 4 5 55 5 0 77 6 5 2 2 32 4 5 55
  • 103. Deleting the root of a heap:  Suppose ‘H’ is a heap with ‘N’ elements and suppose we want to delete the root ‘R’ of ‘H’. This is accomplished as follows:  Assign the root ‘R’ to some variable item.  Replace the deleted node ‘R’ by the last node ‘L’ of ‘H’, so that ‘H’ is still a complete tree, but not necessarily a heap.  Do the heap in the out come tree and again do the above process.
  • 104. Example:  Delete 95: 55 95 85 70 6530 22 33 2015 15 55 22 85 70 653033 2015 15 55 85 22 70 653033 2015 15
  • 105.  Delete 85: 22 85 55 70 653033 2015 15 22 15 55 70 653033 2015
  • 106.  Delete 70: 22 70 55 15 653033 2015 22 85 55 65 153033 2015 22 20 55 65 153033 15
  • 107.  Delete 65: 22 65 55 20 153033 15 22 65 55 30 152033 15 22 15 55 30 152033
  • 108.  Delete 55: 22 55 15 20 153033 22 55 33 30 152015 22 15 33 30 2015
  • 109.  Delete 33: 22 33 15 30 2015 15 33 22 30 2015 15 30 22 20 1515 20 22 30 15
  • 110.  Delete 30:  Delete 22  Delete 20 Delete 15: Delete 15: Nil 15 15 22 20 15 22 15 20 15 15 20 20 15 15 15 15 15
  • 111. Height Balanced Tree/AVL Tree:  In a binary search tree, the effectiveness of searching process always depends upon how data is organized to make up a specific tree.  Searching in a binary search tree is efficient if the heights of both left and right sub-tree of any node are equal.  Frequent insertion and deletion in binary search tree is likely to make it unbalance.  When a binary search tree is not balanced, the operations like searching, insertion, deletion takes considerable time as compared to a binary search tree which is balanced.
  • 112.  The efficiency of searching is ideal, if HL – HR ≤ 1, where HL = left sub-tree and HR = right sub-tree. Such a binary tree is called Balanced Binary Tree.  Balance Factor of a node in binary search tree is the difference between height of left sub-tree and height of right sub-tree of it. BF = HL – HR, where BF = Balance Factor HL = Height of left sub-tree HR = Height of right sub-tree So, a binary search tree is height balanced if all its nodes have a balance factor within the range (-1, 0, 1). So, for every node in a height balanced tree balance factor BF є {-1, 0, 1}.
  • 113.  It was invented in the year 1962, by two Russian Mathematician ADELSON-VELSKII and LANDIS. Hence, such tree is called AVL Tree.  If the height of the right sub-tree is greater than the left sub-tree then BF = -1, if same then BF = 0, if height of value of left sub-tree is greater than right sub-tree then BF = 1.  E.g.: A CB D E F G 1 -1 -1 10 0 0
  • 114. Insertion of a node in an AVL Tree:  Case 1: Insertion of a node as a child of any non- leaf node which has only one child. There will be no effect in the tree. A CB D E F GH
  • 115.  Case 2: Insertion of a node as a child of left node whose parent node has two children of the sub- tree of shorter height there will be no effect on the tree. A CB D E GH I K
  • 116.  Case 3: Insertion of a node as a child of leaf node, where parent node has level zero of sub-tree of same height there will be no effect in the tree. A CB D E GH I
  • 117.  Case 4: Insertion of a node as a child of leaf node of sub-tree of larger height, then the AVL tree become unbalanced and to make it balance we have to perform rotation operation. A CB D E GF H I
  • 118. AVL Rotation:  Assume a tree is balanced initially and the tree becomes imbalanced due to insertion or deletion of a node. Now, in order to make the tree balanced we need to follow certain rotation methods.  There are 4 types of AVL Rotations present.  LL (Left to Left) Rotation  RR (Right to Right) Rotation  LR (Left to Right) Rotation  RL (Right to Left) Rotation  Pivot Node: Pivot node in a binary search tree is the node where the tree gets imbalanced. That is, node for which the balance factor |BF| > 1is treated as pivot node.
  • 119. LL (Left to Left) Rotation:  When the tree gets imbalanced due to insertion of a node at left of the left sub-tree of pivot node, then we follow LL Rotation.  This is the imbalance tree, after inserting a node at sub-tree of node ‘C’. Here pivot node is ‘A’, whose balance factor is 2. A C B AR CL BR CR 2 1 0
  • 120.  Here, ‘CL’ is the left sub-tree of node ‘C’, ‘CR’ is the right sub-tree of node ‘C’, ‘BR’ is the right sub-tree of node ‘B’ and ‘AR’ is the right sub-tree of node ‘A’.  After the rotation of node ‘A’, node ‘A’, becomes the right child of node ‘B’ and ‘BR’ becomes the left child of node ‘A’ as shown below. After rotation the tree becomes balanced. C B CL CR 0 0 A ARBR 0
  • 121. RR (Right to Right) Rotation:  When the tree gets imbalanced due to insertion of a node at right of the right sub-tree of pivot node, then we follow RR Rotation.  After RR Rotation, the tree gets balanced. A C BAL CR BL CL -2 -1 0
  • 122.  Here, unbalanced pivot node ‘A’. ‘AL’ is the left child of ‘A’, ‘BL’ is the left child of ‘B’, ‘CL’ is the left child of ‘C’ and ‘CR’ is the right child of ‘C’  After the Rotation at pivot node ‘A’, the balanced tree is: Where ‘A’ becomes the left child of ‘B’ and ‘BL’ becomes the right child of ‘A’. A B AL BL 0 0 C CRCL 0
  • 123. LR (Left to Right) Rotation:  When the tree gets imbalanced due to insertion of a node at right of the left sub-tree of pivot node, then we follow LR Rotation.  This considered on two rotation. That is:  RR rotation at point ‘B’  LL rotation at pivot point ‘A’ A B AR +2 -1 0CBL CL CR
  • 124.  After performing the ‘RR’ Rotation at ‘B’ the tree becomes:  Since it imbalanced at pivot point ‘A’ we again perform ‘LL’ Rotation at ‘A’. So final balanced tree is: A B C AR BL CR CL 2 1 0 B C BL CL 0 0 A ARCR 0
  • 125. RL (Right to Left) Rotation:  When the tree gets imbalanced due to insertion of a node at left of the right sub-tree of pivot node, then we follow RL Rotation.  Here, to balance the tree, we perform two rotation.  LL rotation at point ‘B’  RR rotation at pivot point ‘A’ A BAL -2 1 0 C BR CRCL
  • 126.  After performing the ‘LL’ Rotation at point ‘B’ the tree becomes:  This is not balanced. So to make it balance again perform RR rotation at point ‘A’. So, the final tree becomes: A B CAL BR CL CR -2 -1 0 B C AL CL 0 0 A BRCR 0
  • 127. Example on Building an AVL Tree:  Construct an AVL Tree from the following sequence of inputs. That is: 50, 60, 70, 15, 10, 33, 22, 35, 25, 40.  Insert 50: : No balancing required.  Insert 60: : No balancing required. 50 0 50 -1 60 0
  • 128.  Insert 70:  Insert 15: : No balancing required RR Rotation50 -2 60 -1 70 0 50 60 70 0 0 0 50 60 70 0 1 1 150
  • 129.  Insert 10:  Insert 33: 50 60 70 0 2 2 151 100 LR Rotation 15 60 70 0 1 0 100 050 15 60 70 0 2 -1 100 150 33 0 LR Rotation 15 50 60 -1 0 0 10 0 033 700
  • 130.  Insert 22: : No Balancing required  Insert 35: : No Balancing required 15 50 60 -1 1 -1 10 0 133 70 0 22 0 15 50 60 -1 1 -1 10 0 033 70 0 22 0 035
  • 131.  Insert 25:  Insert 40: 15 50 60 -1 2 -2 10 0 133 70 0 22 -1 035 025 RL Rotation 22 50 60 -1 1 0 151 033 70 0 25 0 035100 LR Rotation 22 50 60 -1 2 -1 151 -133 70 0 25 0 -1 3510 0 40 0 22 33 50 00 1 151 -1 25 60 0 40 0 -1 35 10 0 70 0
  • 132. Balanced M-way Binary Search Tree/B-Tree:  A node of the tree may contain many records or key and pointers to children. A binary tree is also known as balanced sort tree.  It finds its use in external sorting. It is not a binary tree. To reduce the disk space, accesses and several conditions of the tree must be considered. i.e.  The height of the tree must be kept to a minimum  There must be no empty sub-tree above the leaves of tree.  The leaves of the tree must all be on the same levels  All nodes excepts the leaves must have at least same minimum number of children.
  • 133. Characteristics of B-Tree:  B-Tree of order ‘M’ has the following properties.  Each node has a maximum of ‘M’ children and minimum of M/2 children or any number from 2 to the maximum.  Each node has fewer keys than children will a maximum of M – 1 keys.  Keys are arranged in a defined order within the node. All keys in the sub-tree to the left of a key are predecessors of the key and those on the right are successors of the key.  When a new key is to be inserted into a full node is split into two nodes and the key with the median value is inserted in the parent node is the root, a new root is created.  All levels are on the same level i.e.: there is no empty sub-tree above the level of the leaves.
  • 134. Decision Trees:  Decision tree is a binary tree, where a node represents some decision and edges emanating from a node represent the outcome of the decision.  External nodes represent the ultimate decisions. In fact all the internal nodes represent the local decision, if condition is true, then decision 1, else decision 2 towards a global decision.  E.g.: A > B ? B > C ?A > C ? CBCA T TT F F F Greatest among A, B, C
  • 135. A < B ? B < C ?B < C ? A < C ?A< B< C A < C ? A< C < B B<C<AB<A<CC< A< B C< B< A T F T T T T F F F F Ascending order among A, B, C
  • 136. B+-Tree:  A B+-Tree is an n-ary tree with a variable but often large number of children per node. A B+-Tree consists of a root, internal nodes and leaves. The root may be either a leaf or a node with two or more children.  A B+-Tree can be viewed as a B-Tree in which each node contains only keys and to which an additional level is added at the bottom with linked leaves.  The primary value of a B+-Tree is in storing data for efficient retrieval in block oriented storage context. E.g.: File Systems.
  • 137. Symbol Table Construction:  An important part of any compiler, assembler and loader is the construction and maintenance of a dictionary containing names and their associated values. Such a dictionary is also called a symbol table.  In a typical compiler, there may be several symbol tables corresponding to variable, names, labels, literals etc.  There are number of phases associated with the construction of symbol tables. The building phase involves the insertion of symbols and their associated values, if known into a table.
  • 138.  The referencing phase involves the fetching or accessing of values from a table.  A binary tree structure is chosen for two reasons that is:  a) symbol entries are uniformly distributed according to alphabetical order.  b) A binary tree is easily maintained using a few pointers.  There are some rules to construct symbol table.  Allows variable length character strings  Create trees for variables which are local to a block of program code. This implies that an attempt to insert a duplicate entry is an error. Duplicate entries are permitted as long as they are at different block levels  The symbol table is a set of tree – one for each block level.
  • 139. Graph:  Graph is a non-linear non-primitive data structure, which is used to represent relationship between pairs of elements which are not necessarily hierarchical in nature.  A graph is defined as Graph ‘G’ is an ordered set of vertices or nodes and edges (V, E) which connect themselves, where V(G) represents the set of elements called vertices and E(G) represents the edges between these vertices.
  • 140. Types of Graph:  Undirected Graph: In undirected graph, there is no specific direction associated with the edges.  In general, in an undirected graph an edge is represented by an unordered pair[u, v] and that can be traverse from ‘u’ toward ‘v’ and vice versa  It is a graph such that G = {V, E}, where ‘V’ is set of vertices and ‘E’ is the set of unordered pair of vertices.
  • 141. Example:  Here V = {v1, v2, v3, v4} and E = { e1, e2, e3, e4, e5, e6} i.e.: {(v1, v2), (v2, v3), (v3, v4), (v4, v1), (v1, v3), (v2, v4)} v1 v2 v4 v3 e4 e2 e1 e3 e6 e5
  • 142.  Directed Graph: In Directed Graph, an edge is represented by an ordered pair (u, v) and that can be traversed only from ‘u’ to ‘v’.  It is a graph, such that G = {V, E}, where ‘V’ is set of vertices and ‘E’ is the set of ordered pair of vertices.  If an ordered pair (vi, vj) is in set ‘E’, then there is an edge directed from vi to vj (indicated by arrow sign).  In case of undirected graph a pair (vi, vj) in set ‘E’ is unordered. i.e. (vi, vj) and (vj, vi) are the same edges, but in directed graph they refer to two different edges.
  • 143. Example:  E.g.: Here V = {v1, v2, v3, v4} and E = {(v1, v4),(v1, v3),(v4, v2),(v4, v3),(v3, v2),(v2, v1)} v1 v2 v4 v3
  • 144. Graph Terminology:  Adjacent Vertices: In case of directed graph, the vertex vi is adjacent to another vertex vj, if there is an edge from vi to vj.  In the figure or graph, given below v1 is adjacent to v2 and v4. v4 is adjacent to v2 and v3, v2 is adjacent to v3 but not adjacent to v1.  As an edge ‘E’ is represented by pair of vertices denoted by [u, v], where vertices ‘u’ and ‘v’ are called end points of ‘e’. These vertices are also called adjacent vertices or neighbors. v1 v2 v4 v3
  • 145.  Degree of a node/vertex: For an undirected graph, the degree of vertex ‘vi’ or ‘u’ is the no. of edges connected with it.  For a directed graph, there are two types of degrees. That are in-degree and out-degree.  In-degree: In-degree of a vertex ‘vi’ is number of edges incident into ‘vi’. (i.e.: number of edges ending at vi).  Out-degree: Out-degree of a vertex ‘vi’ is number of edges emanating from ‘vi’. (i.e.: number of edges beginning at vi).  E.g.: v1 v2 v4 v3 In this undirected graph, node ‘v1’ has degree 3, ‘v2’ has degree 2, ‘v3’ has degree 3 and ‘v4’ has degree 2.
  • 146.  In this directed graph, in-degree of v1= 1 and out-degree of v1 = 2. So, degree of v1 = in-degree + out- degree = 1 + 2 = 3.  Similarly, in-degree of v2 = 1 and out-degree of v2 = 2. So degree of v2 = in-degree + out-degree = 1 + 2 =3  In-degree of v3 = 2, out-degree of v3 =1. So, degree of v3 = in-degree + out-degree = 2 + 1 = 3  In-degree of v4 = 2, out-degree of v4 = 1. so, degree of v4 = in-degree + out-degree = 2 + 1 = 3 v1 v2 v4 v3
  • 147.  Source: A vertex ‘u’ is called a source, if it has a out-degree > 0 and in-degree = 0. Here,v1 = source, out-degree = 3 > 0 and in-degree = 0..  Sink: A vertex ‘u’ is called as sink, if it has in- degree > 0 but out-degree = 0. Here,v1 = sink, in-degree = 3 > 0 and out-degree = 0. v1 v4v3v2 v1 v4v3v2
  • 148.  Isolated Vertex: A vertex is isolated if there is no edge, connected from any vertex to that vertex. i.e.: if a node ‘u’ has degree = 0, then that node ‘u’ is called isolated vertex. Here ‘V5’ is an isolated vertex.  Cycle: If there is a path containing edges which start from vertex ‘vi’ and ends at vertex vi, then the path is called cycle. V1 V3 V4 V2 V5
  • 149.  Cyclic Graph: A graph with one or more cycles is known as cyclic graph.  Acyclic Graph: A graph which does not have cycles or cyclic paths, then it is called Acyclic graph. A tree is a acyclic graph. V1 V3 V4 V2 Here, V1→ V2 → V3 → V1 is a cycle and V4→ V1 → V2 → V3 → V4 is another cycle V1 V3 V4 V2 This two figures have no cycles. So, these are Acyclic Graph V1 V2 V3 V5V4
  • 150.  Self Loop: If there is an edge exist, where starting and end vertex are same. i.e. (vi, vi) is an edge, then it is called a self loop.  Parallel/Multiple Edges: In a graph, if there are more than one edge between the same pair of vertices then they are known as the parallel or multiple edges. V1 V3 V4 V2 Here, V2 contains a self loop. Here, parallel or multiple edges exist for the pair of vertices V1, V4. V1 V3 V4 V2
  • 151.  Path: A path ‘P’ of length ‘n’, from a vertex ‘u’ to vertex ‘v’ is defined as sequence of ‘n + 1’ vertices. i.e.: P = {v1, v2, … , vn +1}, such that u = v1 and v = vn + 1  The path is said to be closed if the end points of the path are same. i.e. v1 = vn + 1  The path is said to be simple if all the vertices in the sequence are distinct with the exception that v1 = vn + 1, in that case it is known as closed simple path or loop.  Simple Graph: A graph which does not have parallel edges and self loops, is called simple graph.
  • 152.  Multi Graph: A graph which contains either a self loop or parallel or multiple edges or both is referred as Multi Graph.  Pendant Vertex: A vertex vi is called pendant vertex, if in-degree of vi is 1 and out-degree of vi is 0. V1 V2 V3 V5V4 Here, Pendant Vertices are: V3, V4, V5 contains a self loop. V1 V3 V4 V2
  • 153.  Weighted Graph: A graph is termed as weighted if all the edges are labeled with some weights. A weighted graph can be either directed/undirected.  Complete Graph: A graph ‘G’ is said to be complete if there is a path from each vertex to all other vertices of the graph. v1 v2 v4 v3 v1 v2 v4 v3 9 8 53 9 8 53 v3 v1 v2 v4 v3 v1 v2 v4
  • 154.  Connected Graph: A graph is called connected, if there exist a path from any vertex to any other vertex or for every pair of distinct vertices vi, vj in graph G, there exist a path, then it is connected graph.  A directed graph with this property is called strongly connected, otherwise it is called weakly connected. V1 V3 V4 V2 V1 V3 V4 V2 Strongly connected weakly connected
  • 155. Representation of Graph:  The graph can be represented using:  Sequential/Matrix Representation  Linked List Representation  Sequential/Matrix Representation of graph can be of two types.  Adjacency Matrix  Incidence Matrix
  • 156. Adjacency Matrix:  For representing a graph ‘G’, with ‘N’ number of vertices, a matrix of order N x N size can be considered. v1 v2 v4 v3 Here, if ‘i’ represents row position and ‘j’ represents column position, then if there is an edge from vi to vj, then A[i][j] = 1, else A[i][j] = 0 v1 v2 v3 v4 v1 v2 v3 v4 0 1 0 1 0 0 0 0 1 1 1 0 0 1 0 0 It is a simple way to represent a graph in the form of matrix, and the matrix is called Adjacency matrix.
  • 157. Disadvantages of Adjacency Matrix:  It requires n2 space to represent a graph and also takes n2 time to solve most of the graph related problems.  It may be difficult to insert and delete nodes, because the size of matrix need to be changed and at the same time the sequence of the nodes should be recorded and nodes may be needed to reordered.
  • 158. Incidence Matrix:  In incidence matrix consists of a row for every vertex and column for every edge. v1 v2 v4 v3 Here, if there is an edge ‘Ek’ exist from Vi to Vj , then Vi Ek = 1 and Vj Ek = -1 and others at Ek = 0. So, here for the edge Ek , Vi , Vj are adjacent nodes. v1 v2 v3 v4 e1 e2 e3 e4 1 0 0 -1 -1 -1 0 0 0 1 -1 0 0 0 1 1 e1 e2 e3 e4 e5 -1 0 1 0
  • 159. Linked List Representation:  While representing a graph in linked list format the structure of the node will be as follows.  Here, every vertex consists of 3 parts. That is:  Next: Pointer to the next vertex in the graph.  Vertex: Consists of vertex name.  List: Points to the 1st node of adjacency list of a vertex.  In case of directed graph, it points to the successor nodes or adjacency nodes connected with out-degree edges. Next Vertex List
  • 160. Example:  The adjacency list for the graph is:  The list representation contains node lists and edges list given as follows: A D E B C Node Adjacency List A B, C, D B C C - D C, E E C
  • 162. Graph Traversal:  A graph can be traversed in two standard ways. That are:  Depth First Search(DFS) and  Breadth First Search(BFS)  Depth First Search(DFS): It is a type of graph traversal where we use the concept of stack simply stack.  Breadth First Search(BFS): It is a graph traversal method, which is use the concept of Queue and it is similar to level by level examination of an ordered tree.
  • 163. Depth First Search(DFS) Algorithm:  During the execution of this traversal, we consider 3 states. That is:  Flag = 1, represents Ready State  Flag = 2, represents Waiting State  Flag = 3, represents Processed State  The algorithm for this is:  [Assume Graph ‘G’ with nodes. This algorithm will traverse in DFS order by using a stack].  Step 1: [Initialize all nodes to ready state] Set Flag = 1 for all the nodes  Step 2: [Consider a node as 1st node and push into stack] PUSH(1)
  • 164.  Step 3: [Change the status of node 1 to waiting state] Set Flag = 2 for node 1  Step 4: Repeat while stack is not empty Step 4.1: Set X = POP() Step 4.2: Process X Step 4.3: [Change status of X into Processed State] Set Flag = 3 for node X Step 4.4: Repeat for all adjacent nodes of X, say Y Step 4.4.1: if Flag = 1, for node Y, then PUSH(Y) Set Flag = 2 for node Y [End of if – Step 4.4.1] [End of for – Step 4.4]  Step 5: Exit
  • 165. Example:1  The adjacency list for the graph is:  Flag = 1, Ready state: (A, B, C, D, E)  Ready State(B, C, D, E): Flag 1 Waiting State(A): Flag 2 Stack(A) A D E B C Node Adjacency List A B, C, D B C C - D C, E E C A
  • 166.  Ready State(E): Flag 1 Waiting State(B, C, D): Flag 2 Processed State(A): Flag 3 Stack(B, C, D)  Ready State() Waiting State(B,C,E): Flag 2 Processed State(A, D): Flag 3 Stack(B, C, E)  Ready State() Waiting State(B, C) Processed State(A, D, E) Stack(B, C) C D B C E B C B
  • 167.  Ready State() Waiting State(B) Processed State(A, D, E, C) Stack(B)  Ready State() Waiting State() Processed State(A, D, E, C, B) Stack(Empty)  So, sequence of vertex in above graph for DFS: A, D, E, C, B. B
  • 168. Example:2  Traverse the graph given below in DFS order beginning with node ‘i’. The adjacency list for the graph is:  Flag = 1, Ready state: (A, B, C, D, E, F, G, I, J) Node Adjacency List A B, D, C B E C G, D D B E D F E, D, I G D, F I E, J J F, G a b d c e f g i j
  • 169.  Ready State(A, B, C, D, E, F, G, J): Flag 1 Waiting State(I): Flag 2 Processed State() Stack(I)  Ready State(A, B, C, D, F, G): Flag 1 Waiting State(E, J): Flag 2 Processed State(I): Flag 3 Stack(E, J)  Ready State(A, B, C, D): Flag 1 Waiting State(E, F, G): Flag 2 Processed State(I, J): Flag 3 Stack(E, F, G) J E I F G E
  • 170.  Ready State(A, B, C): Flag 1 Waiting State(E, F, D): Flag 2 Processed State(I, J, G): Flag 3 Stack(E, F, D)  Ready State(A, C): Flag 1 Waiting State(E, F, B): Flag 2 Processed State(I, J, G, D): Flag 3 Stack(E, F, B)  Ready State(A, C): Flag 1 Waiting State(E, F): Flag 2 Processed State(I, J, G, D, B): Flag 3 Stack(E, F) F B E F D E F E
  • 171.  Ready State(A, C): Flag 1 Waiting State(E): Flag 2 Processed State(I, J, G, D, B, F): Flag 3 Stack(E)  Ready State(A, C): Flag 1 Waiting State() Processed State(I, J, G, D, B, F, E): Flag 3 Stack(Empty)  So, the processes nodes in DFS, starting from node ‘i’ is as follows: I, J, G, D, B, F, E.  NOTE: There are certain nodes which can not be traversed as there exist no path from node ‘i’, which are present in Ready State i.e.: A, C E
  • 172. Breadth First Search(BFS) Algorithm:  During the execution of this traversal, we consider 3 states. That is:  Flag = 1, represents Ready State  Flag = 2, represents Waiting State  Flag = 3, represents Processed State  The algorithm for this is:  [Assume Graph ‘G’ with ‘n’ nodes. This algorithm will traverse the graph in breadth first order by using a queue].  Step 1: [Initialize all nodes to ready state] Set Flag = 1 for all the nodes  Step 2: [Consider a node as 1st node and insert into queue] Insert(1)
  • 173.  Step 3: [Change the status of node 1 to waiting state] Set Flag = 2 for node 1  Step 4: Repeat while queue is not empty Step 4.1: Set X = Delete() Step 4.2: Process X Step 4.3: [Change status of X into Processed State] Set Flag = 3 for node X Step 4.4: Repeat for all adjacent nodes of Y of X Step 4.4.1: if Flag = 1, for node Y, then Insert(Y) Set Flag = 2 for node Y [End of if – Step 4.4.1] [End of for – Step 4.4] [End of for – Step 4]  Step 5: Exit
  • 174. Example:  The adjacency list for the graph is:  Flag = 1, Ready state: (A, B, C, D, E)  Ready State(B, C, D, E): Flag 1 Waiting State(A): Flag 2 Queue(A) A D E B C Node Adjacency List A B, C, D B C C - D C, E E C 0 1 2 3 4 F = R = -1 A 0 1 2 3 4 F = R = 0
  • 175.  Ready State(E): Flag 1 Waiting State(B, C, D): Flag 2 Processed State(A): Flag 3 Queue(B, C, D)  Ready State(E) Waiting State(C, D): Flag 2 Processed State(A, B): Flag 3 Queue(C, D)  Ready State(E) Waiting State(D) Processed State(A, B, C) Queue(D) B C D 0 1 2 3 4 F = 1, R = 3 C D 0 1 2 3 4 F = 2, R = 3 D 0 1 2 3 4 F = 3, R = 3
  • 176.  Ready State() Waiting State(E) Processed State(A, B, C, D) Queue(E)  Ready State() Waiting State() Processed State(A, B, C, D, E) Queue(Empty)  So, sequence of vertex in above graph for DFS: A, B, C, D, E. E 0 1 2 3 4 F = 4, R = 4 0 1 2 3 4 F = -1, R = -1
  • 177. Example:2  Find the BFS order of the graph as shown in given figure starting from node a to j . The adjacency list for the graph is: Node Adjacency List A B, D, C B E C G, D D B E D F E, D, I G D, F I E, J J F, G a b d c e f g i j
  • 178.  Flag = 1, Ready state: (A, B, C, D, E, F, G, I, J)  Ready State(B, C, D, E, F, G, I, J): Flag 1 Waiting State(A): Flag 2 Processed State() Queue(A)  Ready State(E, F, G, I, J): Flag 1 Waiting State(B, D, C): Flag 2 Processed State(A): Flag 3 Queue(B, D, C) A 0 1 2 3 4 5 6 7 Front = 0, Rear = 0 0 1 2 3 4 5 6 7 Front = -1, Rear = -1
  • 179.  Ready State(F, G, I, J): Flag 1 Waiting State(D,C,E): Flag 2 Processed State(A, B): Flag 3 Queue(D, C, E)  Ready State(F, G, I, J): Flag 1 Waiting State(C, E): Flag 2 Processed State(A, B, D): Flag 3 Queue(C, E) D C E 0 1 2 3 4 5 6 7 Front = 2, Rear = 4 B D C 0 1 2 3 4 5 6 7 Front = 1, Rear = 3
  • 180.  Ready State(F, I, J): Flag 1 Waiting State(E, G): Flag 2 Processed State(A, B, D, C): Flag 3 Queue(E, G)  Ready State(F, I, J): Flag 1 Waiting State(G): Flag 2 Processed State(A, B, D, C, E): Flag 3 Queue(G) E G 0 1 2 3 4 5 6 7 Front = 4, Rear = 5 C E 0 1 2 3 4 5 6 7 Front = 3, Rear = 4
  • 181.  Ready State(I, J): Flag 1 Waiting State(F): Flag 2 Processed State(A, B, D, C, E, G): Flag 3 Queue(F)  Ready State(J): Flag 1 Waiting State(I): Flag 2 Processed State(A, B, D, C, E, G, F): Flag 3 Queue(I) F 0 1 2 3 4 5 6 7 Front = 6, Rear = 6 G 0 1 2 3 4 5 6 7 Front = 5, Rear = 5
  • 182.  As we reached our destination node ‘I’, we now backtrack from ‘I’ by going backward direction of processed state, we get our path our shown below: I ← F ← G ← C ← A I 0 1 2 3 4 5 6 7 Front = 7, Rear = 7
  • 183. Topological Sorting:  For performing the tasks serially, an acyclic directed graph can be represented in linear order of nodes, which is called topological sorting.  So, if the graph is finite directed graph without cycles, there exist a topological sort. A G F B D CE Adjacency Lists A C B D, F C - D C E C F - G A, F
  • 184. Algorithm:  [Consider a graph ‘G’ without cycles, this algorithm finds the topological order of graph ‘G’].  Step 1: Find the in-degree(n) of each node ‘n’ of graph ‘G’.  Step 2: Insert all the nodes with ‘0’ in-degree into Queue.  Step 3: Repeat until Queue is empty. Step 3.1: Remove the front node ‘n’ of the Queue. Step 3.2: Repeat for each neighbor ‘m’ of node ‘n’. Step 3.2.1: Set in-degree(m) = 0, then in-degree(m) – 1. Step 3.2.2: If in-degree(m) = 0, then insert it at rear end of Queue [End of for – Step 3.2] [End of loop – Step 3]  Step 4: Exit
  • 185.  Here, in the given figure, in-degree of A = 1, in- degree of C = 3, in-degree of F = 2, in-degree of D = 1, in-degree of B = 0, in-degree of E = 0 and in- degree of G = 0.  The nodes having zero in-degrees are putting in a Queue. i.e.  Remove ‘B’ and adding its vertex ‘D’ and ‘F’. ‘D’ having in-degree = 1 and ‘F’ having in-degree = 2. So, in-deg(D) = 1-1 = 0 and in-deg(F) = 2 – 1 = 1. B E GQ 0 1 652 3 4 F = 0, R = 2 7 E G DQ 0 1 652 3 4 F = 1, R = 3 7
  • 186.  Remove ‘E’ and adding its vertex ‘C’. ‘C’ having in-degree = 3. So, in-deg(C) = 3-1 = 2.  Removing ‘G’ and adding ‘A’ and ‘F’. So in-deg(A) = 1 -1 = 0 and in-deg(F) = 1 - 1 = 0.  Removing ‘D’ and adding ‘C’. So, in-deg(C) = 2 -1 = 1 G DQ 0 1 652 3 4 F = 2, R = 3 7 D A FQ 0 1 652 3 4 F = 3, R = 5 7 A FQ 0 1 652 3 4 F = 4, R = 5 7
  • 187.  Removing ‘A’ and adding ‘C’. So, in-deg(C) = 1 -1 = 1.  Removing ‘F’.  Removing ‘C’.  Finally, the Topological Sorting order is: B, E, G, D, A, F, C CQ 0 1 652 3 4 F = 6, R = 6 7 F CQ 0 1 652 3 4 F = 5, R = 6 7 Q 0 1 652 3 4 F = -1, R = -1 and Q is empty 7
  • 188. Path Matrix or Reachability Matrix:  A path matrix contains information about each vertex to other vertex, there exist a path or not. The adjacency matrix for the graph is:v1 v2 v4 v3 v1 v2 v3 v4 v1 v2 v3 v4 0 1 0 1 0 0 1 1 1 0 0 1 1 0 0 0 A = From Adjacency Matrix, we can know, there exist a direct single edge from one node to another or not.
  • 189.  Now consider A2, A3, A4 according to the size of matrix or number of vertices.  Here, A2 represent how many paths exist for a particular node to another node, using two edges v1 v2 v3 v4 v1 v2 v3 v4 1 1 0 1 2 0 1 1 1 0 0 1 0 0 0 0 A2 = v1 v2 v3 v4 v1 v1v4v1 - v2v4v1 v2v3v1 v3v4v1 v2 - v3v1v2 v4v1v2 - v3 v1v2v3 - - - v4 v1v2v4 v2v3v4 v3v1v4 v4v1v4
  • 190.  In A2 matrix, v2 to v1 is having two paths using two edges. That is: v2v4v1 and v2v3v1  Here, A3 shows number of paths exist using 3 edges. v1 v2 v3 v4 v1 v2 v3 v4 2 1 0 1 1 2 0 1 0 1 1 1 0 0 1 1 A3 = v1v2v4v1 v1v2v3v1 v2v3v4v1 --- v1v4v1v2 v2v4v1v2 v2v3v1v2 v3v4v1v2 v3v1v2v3 v4v1v2v3--- --- v1 v2 v3 v4 v1 v2 v3 v4 v1v2v3v4 v2v4v1v4 v3v1v2v4 v4v1v2v4 --- ---
  • 191.  Here, A4 shows number of paths exist using 3 edges.  BN = A + A2 + A3 + …. + AN, where N = total number of nodes. v1 v2 v3 v4 v1 v2 v3 v4 1 0 1 1 0 1 1 1 0 1 1 1 0 1 0 1 A4 = v1v2v3v4v1 --- --- v1 v2 v3 v4 v1 v2 v3 v4 v1v4v1v2v3 --- v1v2v3v1v4 --- v2v3v4v1v2 v3v1v4v1v2 v4v1v4v1v2 v2v4v1v2v3 v3v4v1v2v3 --- v2v3v1v2v4 v3v1v2v3v4 v4v1v2v3v4
  • 192.  So B4 = A + A2 + A3 + A4  Now, by representing all non-zero entries by 1, we obtain path matrix: v1 v2 v3 v4 v1 v2 v3 v4 4 2 2 4 3 3 2 4 2 3 2 4 1 2 1 3 B = v1 v2 v3 v4 v1 v2 v3 v4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 P = So, here P is the path matrix that shows whether there exist a path from one node to other or not. vertices The above matrix shows that there exist a path between any pair of vertices of given graph. If any zeros are present in path matrix, then it suggests that no path exist for those pair of vertices
  • 193. Shortest Path Problems:  The problem in a graph is about finding a path between two vertices in such a way that this path will satisfy some conditions.  In a non-weighted graph, to find a shortest path, we count the number of edges. In a weighted graph, the shortest path is determined by sum of the weights on edges in a path.  The different types of algorithm used for this problem is:  Warshall’s Algorithm  Floyd’s Algorithm  Dijkstra’s Algorithm
  • 194. Warshall’s Algorithm:  It is basically used to find the path matrix for a given graph.  By using this, one can specify whether there exists a path between two vertices or not.  Assume a directed graph ‘G’ with ‘N’ nodes is maintained in memory by its adjacency matrix ‘A’.  This algorithm finds path matrix ‘P’ of graph ‘G’.
  • 195. Algorithm:  Assume ‘A’ is an adjacency matrix of order N x N order. This algorithm find the path matrix ‘P’. Step 1: Let I, J, K Step 2: Repeat for I = 1 to N incrementing by 1 Step 2.1: Repeat for J = 1 to N incrementing by 1 Step 2.1.1: if A[I][J] = 0, then set P[I][J] = 0 Step 2.1.2: else set P[I][J] = 1 [End of if] [End of for] [End of for]
  • 196. Step 3: Repeat for K = 1 to N incrementing by 1 Step 3.1: Repeat for I = 1 to N incrementing by 1 Step 3.1.1: Repeat for J = 1 to N incrementing by 1 P[I][J] = P[I][J] U (P[I][K] ∩ P[K][J]) [End of for] [End of for] [End of for] Step 4: Exit
  • 197. All Pair Shortest Path: Floyd’s Algorithm:  By using Warshall’s algorithm, one can find path matrix which shows presence or absence of path between a pair of vertices.  If a weighted graph exists and we are interested to find the length of shortest path between any pair of vertices, then we follow Floyd’s algorithm for this purpose.
  • 198. Algorithm:  Assume ‘W’ is a matrix of N x N order that represents a weighted graph. This finds a matrix ‘Q’ of N x N order which represents the shortest path from any vertex to any vertex. Step 1: Let I, J, K Step 2: Repeat for I = 1 to N incrementing by 1 Step 2.1: Repeat for J = 1 to N incrementing by 1 Step 2.1.1: if W[I][J] = 0, then set Q0[I][J] = ∞ Step 2.1.2: else set Q[I][J] = W[I][J] [End of if] [End of for] [End of for]
  • 199. Step 3: Repeat for K = 1 to N incrementing by 1 Step 3.1: Repeat for I = 1 to N incrementing by 1 Step 3.1.1: Repeat for J = 1 to N incrementing by 1 Set QK[I][J]= MIN(QK-1[I][J], QK-1[I][K] + QK-1[K][J]) [End of for] [End of for] [End of for] Step 4: Exit
  • 200. Example:  Consider a directed graph as shown in given figure.  The corresponding weighted matrix is: A D B C 6 8 7 5 4 3 2 A B C D A B C D 8 6 0 0 7 0 0 3 0 4 0 0 5 0 2 0 W = In step 2, we store the details of weighted matrix into ‘Q’. Using this algorithm, we obtain Q0, Q1, Q2, Q3 and Q4, where K = 0 to 4
  • 201.  ‘Q0’ represents the minimum weight between each pair of nodes using single edge. i.e.:  ‘Q1’ represents minimum weight in between each weight at ‘Q0’ and each weight obtained using intermediate vertex ‘A’. A B C D A B C D 8 6 ∞ ∞ 7 ∞ ∞ 3 ∞ 4 ∞ ∞ 5 ∞ 2 ∞ Q0 = => A B C D A B C D AA AB -- -- BA -- -- BD -- CB DA DC-- -- -- -- A B C D A B C D 8 6 ∞ ∞ 7 13 ∞ 3 ∞ 4 ∞ ∞ 5 11 2 ∞ Q1 = => A B C D A B C D AA AB -- -- BA BAB -- BD -- CB DA DCDAB -- -- --
  • 202.  E.g. at Q0, B-B using single edge is ∞. So, now BAB using two edges, it is 13. So, minimum distance is B, updated at Q1.  ‘Q2’ represents minimum weight in between each weight at ‘Q1’ and each weight obtained using intermediate vertex ‘B’. E.g. At, Q1, C-D is ∞, and now CBD is 7. So, minimum distance ‘7’ is updated at Q2. A B C D A B C D 8 6 ∞ 9 7 13 ∞ 3 11 4 ∞ 7 5 11 2 14 Q2 = => A B C D A B C D AA AB -- BA BAB -- BD CB DA DCDAB CBD-- ABD CBA DABD
  • 203.  ‘Q3’ represents minimum weight in between each weight at ‘Q2’ and each weight obtained using intermediate vertex ‘C’. E.g. At, Q2, D-B is 11, and now DCB is 6. So, minimum distance ‘6’ is updated at Q3.  ‘Q4’ represents minimum weight in between each weight at ‘Q3’ and each weight obtained using intermediate vertex ‘D’. E.g. At, Q3, BAB is 13, and now BDC is 9. So, minimum distance ‘9’ is updated at Q4. A B C D A B C D 8 6 ∞ 9 7 13 ∞ 3 11 4 ∞ 7 5 6 2 9 Q3 = => A B C D A B C D AA AB -- BA BAB -- BD CB DA DCDCB CBD-- ABD CBA DCBD
  • 204.  Finally, we get possible shortest path between every pair of vertices. i.e. at Q4. In the above algorithm, we obtain these at matrix ‘Q’. A B C D A B C D 8 6 11 9 7 9 5 3 11 4 9 7 5 6 2 9 Q4 = => A B C D A B C D AA AB BA BDCB BDC BD CB DA DCDCB CBDCBDC ABD CBA DCBD ABDC
  • 205. Dijkstra’s Algorithm:  Dijkstra’s algorithm is an algorithm for solving the singe source shortest path problem in a weighted graph.  Here we consider a distinct vertex as source and the algorithm will find the shortest possible path from source to all other vertices of the graph.  So, this algorithm is called single source shortest path algorithm.
  • 206. Algorithm:  Step 1:V = {1, 2, 3, 4, 5, 6}  Step 2: S = {1}  Step 3: Repeat for i = 2 to N incrementing by 1 D[i] = C(1, i) [End of for]  Step 4: Repeat for I = 1 to N - 1 incrementing by 1  Step 4.1: Choose a vertex w in {V – S}, such that D[w] is minimum.  Step 4.2: Add w to S  Step 4.3: Repeat for each vertex U in {V – S} D[U] = min(D[U], D[w]+C(w, U)) [End of for]  Step 5: Exit
  • 207. Example:  Consider the graph where source is vertex ‘1’.  ‘V’ is set of vertices i.e. V = {1, 2, 3, 4, 5, 6}.  ‘S’ is set of source vertices, initially S = {1}.  ‘C’ is cost/weight of an edge.  ‘N’ identifies total number of nodes  D[N] is an array which contains the distance/weight of each vertex from source.  ‘W’ is the vertex with minimum weight in the list of {V – S}.  ‘V’ identifies each vertex of {V – S}.
  • 208. Evolution Process: V = {1, 2, 3, 4, 5, 6}, S = {1} D[N] =  Here, consider vertex 1, at cost ∞. Now, from vertex 1 to each vertex cost is C(1, i). 1 2 3 4 5 6 90 40 ∞ 10 ∞90 70 60 1 2 43 5 6 i
  • 209.  C(1, 2) => 1 to 2 = 10 C(1, 3) => 1 to 3 = 90 C(1, 4) => 1 to 4 = ∞ C(1, 5) => 1 to 5 = 70 C(1, 6) => 1 to 6 = 60  When i = 1,  Step 4:  Step 4.1: V – S = {2, 3, 4, 5, 6}. Now identify minimum cost D[w] from 2 to 6 positions. i.e. w = 2  Step 4.2: Add ‘w’ i.e. 2 to S, So, S = {1, 2} ∞ 10 ∞90 70 60 1 2 43 5 6 i ∞ 10 ∞90 70 60 1 2 43 5 6 U
  • 210.  Step 4.3: When U = 3, D[3] = min(D[3], D[2] + C(2, 3)) = min(90, 10 + 20) = min(90, 30). So, D[3] = 30  Step 4.4: when i = 2, V = {3, 4, 5, 6}  Identify minimum cost D[w] from 3 to 6. That is minimum cost is 30. i.e. w = 3.  Add w to S = {1, 2, 3}. So V – S = {4, 5, 6} ∞ 10 ∞30 70 60 1 2 43 5 6
  • 211.  When U = 4, D[4] = min(D[4], D[3] + C(3, 4)) = min(∞, 30 + 30) = 60. So, D[4] = 60  Step 4.5: when i = 3, V = {4, 5, 6}  Identify minimum cost D[w] from 4 to 6. That is minimum cost is 60. i.e. w = 4.  Add w to S, So S = {1, 2, 3, 4}. So V – S = {5, 6}. Now,  D[U] = min(D[U], D[w] + C(w, U)) i.e.  D[U] = min(D[5], D[4] + C(4, 5)) = min(70, 60 + ∞) = 70. So, D[5] = 70. ∞ 10 6030 70 60 1 2 43 5 6
  • 212.  Step 4.6: when i = 4, V = {5, 6}  Identify minimum cost D[w] from 5 to 6. That is minimum cost is 60. i.e. w = 5.  Add w to S, So S = {1, 2, 3, 4,5}. So V – S = {6}. Now,  D[6] = min(D[6], D[5] + C(5, 6)) = min(60, 70 + ∞) = 60. So, D[6] = 60. ∞ 10 6030 70 60 1 2 43 5 6 ∞ 10 6030 70 60 1 2 43 5 6 End