You are on page 1of 220

NON-LINEAR DATA

STRUCTURES

Classification of Data
Structures

Classification of Data
Structures
Non-Primitive Data Structure

TREES

Trees - Introduction
A tree is an abstract data type that stores

elements hierarchically.
With the exception of the top element, each

element in a tree has a parent element and


zero or more children elements.
The top element is the root of the tree, but it

is drawn as the highest element, with the


other elements being connected below (just
the opposite of a botanical tree).

Some Key Terms:


Root Node at the top of the tree is called root.
Parent Any node except root node has one edge upward to a node called parent.
Child Node below a given node connected by its edge downward is called its child

node.
Sibling Child of same node are called siblings
Leaf or Terminal Node which does not have any child node is called leaf (Terminal)

node.
Sub tree Sub tree represents descendants of a node.
Levels Level of a node represents the generation of a node. If root node is at level 0,

then its next child node is at level 1, its grandchild is at level 2 and so on.
keys Key represents a value of a node based on which a search operation is to be

carried out for a node.

Example of a Tree
No. of nodes = 9
Height = 4
Highest level = 3
Root node = 8
Leaves = 1,4,7,13
Interior nodes = 3,10,6,14
Ancestors of 6 = 3,8
Descendants of 10 = 14,13
Sibling of 1 = 6

Some Key Terms:

Degree of a node:

The degree of a node is the number of children of that node

Degree of a Tree:
The degree of a tree is the maximum degree of nodes in a given tree

Path:
It is the sequence of consecutive edges from source node to destination

node.
Height of a node:
The height of a node is the max path length from that node to a leaf node.

Height of a tree:
The height of a tree is the height of the root

Depth of a tree:
Depth of a tree is the max level of any leaf in the tree

Degree of the tree = 4


(Max degree of A)

Level 1

Height of the tree = 4


(Max level)

Level 2

Level 3

Level 4

Characteristics of trees
Non-linear data structure
Combines advantages of an ordered array
Searching as fast as in ordered array
Insertion and deletion as fast as in linked list

BINARY TREES

Binary Tree
A binary tree T is defined as a finite set of elements, called nodes,

such that
a)

T is empty (Null tree or empty tree)

b)

T contains a distinguished node R, called the root of tree T , and the


remaining nodes of T form an ordered pair of disjoint binary trees of T1
and T2.

If T contains a root R, then the two trees T1 and T2 are called

respectively, the left and right subtrees of R.


If T1 is non-empty, then its root is called the left successor of R
Similarly if T2 is non-empty, then its root is called the right successor

of R

Binary Tree Properties


If a binary tree contains m nodes at level L, it

contains at most 2m nodes at level L+1

Since a binary tree can contain at most 1 node at

level 0 (the root), it contains at most 2L nodes at


level L.

Binary Tree

Binary Tree
A binary tree is a tree in which no node can

have more than two children


root

Level 1

TL

TR

Level 2

C
E

Level 3

Binary Trees
Consider a binary tree T, here A is the

root node of the binary tree T.


B is the left child (successor) of A and

C is the right child (successor) of A


i.e. A is a father of B and C.
The node B and C are called siblings.

Nodes D,H,I,F,J are leaf node

Expression Trees

(a+b*c)+((d*e+f)*g)

The following figure shows a binary tree with 9


nodes where A is the root

The node of a binary tree is divided into three parts :


Left child Address

Left

Info

Right

Right child Address

Binary Tree
The root node of this binary tree is A.
The left sub tree of the root node, which we denoted by LA, is

the set LA = {B,D,E,G} and the right sub tree of the root node,
RA is the set RA={C,F,H}
The root node of LA is node B, the root node of RA is C and so

on

CLASSIFICATION OF
BINARY TREE

1.

Classification of Binary Tree


Strictly Binary Tree:

If every non-leaf node in a binary tree has nonempty left and right subtrees,
the tree is termed a strictly binary tree.

Each node in a tree is either Leaf or has exactly two children

Strictly binary tree with n Leaves always contains 2n-1 nodes


E.g.
2 Leaves in First Example having 2*2-1=3 Nodes.
3 Leaves in Second Example having 3*2-1=5 Nodes.
4 Leaves in Third Example having 4*2-1=7 Nodes

Classification of Binary Tree


2. Complete Binary Tree is a Strict Binary tree in which every leaf node is at
same level.
That means, there are equal number of children in right and left
subtree for every node
The total number of nodes in a complete binary tree of depth d equals
2d+1 1.
Since all leaves in such a tree are at level d, the tree contains 2d leaves
and, therefore, 2d - 1 internal nodes including root of the tree.

Classification of Binary Tree

3.

Almost Complete Binary Tree:


A binary tree in which all the terminal
node or leaf node of tree are at level
d or d-1, where d is the depth of
tree, then such trees are

called

almost complete binary tree.

An almost complete binary tree with


N leaves that is not strictly binary
has 2N nodes.

For any node nd in the tree with a


right descendant at level d, all the
left

descendants

of nd that

leaves are also at level d.

are

Classification of Binary Tree

4. Extended Binary Tree:

If in a binary tree, each empty sub tree (Leaf Node) is replaced by a


special node then the resulting tree is extended binary tree or 2-tree

We can add special node to leaf node & node that have only one child.
The special nodes added to the tree are called External Node & original
node of tree are called Internal Node

Internal Node

Binary Tree
External Node
Extended Binary Tree
Note: Binary Tree of Height h has maximum (2 h+1 - 1) nodes

REPRESENTATION OF
BINARY TREE

Representation
of
Tree
1. Sequential Representation using array
Tree is store in single array
Number are assigned to each node from leftmost to rightmost node.
Root node always assign no. 1
Left Child is placed at position [2 * K] (k is position of root)
Right Child is placed at position [2 * K + 1]
Size of array is Depends on Depth of tree i.e. 2 d+1

1
A

2
B

3
C

4
D

5
E

A 1
3
C

2
B
4

5
E

D
8

9
H

6
F

7
G

6
F

7 8
G H

9
I

Root (A) =1
L Child = [2*k]= 2 * 1 =2 (B)
R child = [2 * K + 1] = 2 * 1 + 1 = 3 (C)
Root(B)=2
L Child = [2*k]= 2 * 2 =4 (D)
R child = [2 * K + 1] = 2 * 2 + 1 = 5 (E)
Note: If root is placed at 0th position then
L Child = [2 * k + 1 ]
R child = [2 * K + 2 ]

Representation
of
Tree
2. Linked Representation using array

Tree is store in single array


1
A
2

3
B

5
D

E.g.

2 A 3

6
F

7
G

Structure of Node
Struct mode
{
Int Left;
Int Info;
Int Right;
};
Node Tree[10];
Tree [ 1] . Info = A
Tree [ 1 ] . Left = 2
Tree [ 1 ] . Right = 3

Representation of Tree
3. Linked Representation using Pointer
Right

Left Info
E.g.

Structure of Node
Struct node
{
node *Left;
Int Info;
node *Right;
};
node *root;

1
A
2

3
B

5
D

Ptr -> Info = Data

7
F

Ptr -> Left = Left Child


Ptr -> Right = Right Child

Note:
If n number of node in B.T. then total number of null link will be n+1
If tree is empty then root will be NULL

BINARY SEARCH
TREE

Binary Search Tree


An application of binary trees is their use in searching
Let us assume that each node in the tree is assigned

a key value, and assume that this is an integer


The property that makes a binary tree into a binary

search tree is that


X

Smaller values in left subtree


Larger values in right subtree
Example
X>Y
X<Z

Example:
k

All<kA

Allkk

20

30

10

12

25

35

Binary Search Tree


Examples
5
10
5

10

45

30

45

30
2

25

45

10

25

30

25
Binary
search trees

Not a binary
search tree

Difference between BT and BST


A binary tree is simply a tree in which each node can have at most two

children.
A binary search tree is a binary tree in which the nodes are assigned

values, with the following restrictions :


1.No duplicate values.
2.The left subtree of a node can only have values less than the node
3.The right subtree of a node can only have values greater than the node

and recursively defined


4.The left subtree of a node is a binary search tree.
5.The right subtree of a node is a binary search tree.

Binary Tree Search Algorithm


TREE-SEARCH (x (the current node being inspected),k(the number to be
found)
If x==NIL or k==x.key (key-Key represents a value of a node based

on which a search operation is to be carried out for a node.)


return x
If k < x.key
return TREE-SEARCH(x.left,k)
else
return TREE-SEARCH(x.right,k)

BST Operations
Four basic BST operations
1

Traversal
2

Search

Insertion
4

Deletion

TRAVERSING BINARY
TREE

Tree traversal

Traversal is a process to visit all the nodes of a tree and may

print their values too.


All nodes are connected via edges (links) we always start

from the root (head) node.


There are three ways which we use to traverse a tree
In-order Traversal
Pre-order Traversal
Post-order Traversal

Generally we traverse a tree to search or locate given

item or key in the tree or to print all the values it


contains.

Pre-order, In-order, Post-order


Pre-order (RLN)

<root><left><right>
In-order (LNR)

<left><root><right>
Post-order (LRN)

<left><right><root>
N Node
L Left subtree
R Right subtree

Pre-order
Traversal

The preorder traversal of a nonempty binary tree is defined


as follows:
Visit the root node
Traverse the left sub-tree in preorder
Traverse the right sub-tree in preorder

Pre-order Traversal
Root

Left

23 18 12 20 44 35 52

Right

In-order traversal
The

in-order

traversal

of

nonempty binary tree is defined


as follows:
Traverse the left sub-tree in in-order
Visit the root node
Traverse the right sub-tree in in-order

The in-order traversal output of

the given tree is


HDIBEAFCG

In-order Traversal
Left

Root

Right

12 18 20 23 35 44 52

Post-order traversal
The

in-order

traversal

of

nonempty binary tree is defined as


follows:
Traverse the left sub-tree in post-order
Traverse the right sub-tree in post-

order
Visit the root node

The in-order traversal output of the

given tree is
HIDEBFGCA

Post-order Traversal
Left

Right

Root

12 20 18 35 52 44 23

Constructing Binary Tree

reconstruction.exe

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Constructing Binary Tree

Evaluate postfix expression using


stack

evaluation.exe

Searching Through The BST


Compare the target value with the element in the root

node
If the target value is equal, the search is successful.
If target value is less, search the left subtree.
If target value is greater, search the right subtree.
If the subtree is empty, the search is unsuccessful.

Binary Search Tree (Search)


Search for 10

20

10

50

Binary Search Tree (Minimum)


6

-5
-1

20

10

50

Binary Search Tree (Maximum)


50
45

70
80

40
30

42

75

85
90

Insertion of a node in BST


1. To insert a new item in a tree, first verify that its key(we must

make sure that each value nthe BST is unique) is different


from those of existing elements.
2. If a new value is less, than the current node's value, go to the

left subtree, else go to the right subtree.


3. Following this simple rule, the algorithm reaches a node,

which has no left or right subtree.


4. By the moment a place for insertion is found, make sure that,

a new value has no duplicate in the tree.

Algorithm for insertion in BST


Check, whether value in current node and a new value

are equal. If so, duplicate is found. Otherwise,

if a new value is less, than the node's value:


if a current node has no left child, place for insertion has been found;
otherwise, handle the left child with the same algorithm.

if a new value is greater, than the node's value:


if a current node has no right child, place for insertion has been found;
otherwise, handle the right child with the same algorithm.

Binary Search Tree (Insert)


6

Insert 20, 10, 50

20

10

50

Binary Search Tree (Insert)


Lets insert 6, 2, 4, 3, 1, 8 and 11 in an empty BST

11

Binary Search Tree (Insert)


Try inserting 1, 2, 3, and 4 in an empty BST.
1

BST (Delete)
In deletion, we dont ask for a position. We ask for the

actual item that has to be deleted.

Deleting a leaf

11

Deleting a node with one child


3

Deleting a node with two children

Deleting a node from the BST


While deleting a node from BST, there may be three cases:
1.The node to be deleted may be a leaf node:
In this case simply delete a node and set null pointer to its parents

those side at which this deleted node exist.

Deleting a Leaf (-1)


6

case1.exe

-5
-1

20

10

50

Deleting a node from the BST


2. The node to be deleted has one child
In this case the child of the node to be deleted is appended

to its parent node. Suppose node to be deleted is 18

Deleting a Node with a Child(-5)


6

-5
-1

case3.exe

20

10

50

Deleting a node from the BST

Deleting a node with two children


(2)
6

2
3

-5
-1

case2.exe

20

10

50

THREADED BINARY
TREE

Threaded
Binary
Tree
A binary tree with n nodes has 2n pointers(one for the left node and another for the right

node) out of which n+1 (because the pointers in the leaves are always null)are always
NULL, So about half the space allocated for pointers is wasted
Utilize this wasted space to contain some useful information
A left NULL pointer can be used to store the address of inorder predecessor of the node
A right NULL pointer can be used to store the address of inorder successor of the node.
These pointers are called threads and a binary tree which implements these pointers

is called a Threaded Binary Tree

Example
A
B

N C N

N D N

N F N

N G N

Right in-Threaded Binary Tree

A
B

N C N
E

N D

N F

N G

LEFT in-Threaded Binary Tree

A
B

C N

N D N

F N

G N

Fully in-Threaded Binary Tree


A
B

C N

N D

Drawbacks of Binary Search


Tree

The Disadvantage of a Binary Search Tree is that its Height


can be as large as N.

This means that the time needed to perform Insertion and


deletion and many other operations can be O(N) in the worst
case.

Can be removed using Height Balanced Binary Tree AVL


tree

Complexity in BST
Operation

Average

Worst Case

Best Case

Search

O(log n)

O(n)

O(1)

Insertion

O(log n)

O(n)

O(1)

Deletion

O(log n)

O(n)

O(1)

ADELSON-VELSKI LANDIS
(AVL) TREE

AVL Tree
Adelson-Velski Landis (AVL) Tree
AVL tree is a self-balancing Binary Search Tree
(BST) where the difference between heights of left
and right subtrees cannot be more than one for all
nodes.

Balance factor = Height of left subtree Height of right


subtree
If balance factor of all node is (-1 or 0 or 1) then the tree is
said to be a Balanced Tree ( AVL-TREE)

AVL-TREE

NOT AN AVL-TREE

Right Rotate

Left-Rotate

Left-Right Rotate

Right-Left Rotate

Applications of BST
Used in many search applications where data is constantly
entering/leaving, such as the map and set objects in many
languages' libraries.
Storing a set of names, and being able to lookup based on a
prefix of the name. (Used in internet routers.)
Storing a path in a graph, and being able to reverse any
subsection of the path in O(log n) time. (Useful in travelling
salesman problems).
Finding square root of given number
Allows you to do range searches efficiently.

SETS & UNION / FIND


STRUCTURES

The Set ADT


A set is a collection of distinct objects.
That is, there are no duplicate elements in a set,

and there is no explicit notion of keys or even an


order.
Even so, if the elements in a set are comparable,

then we can maintain sets to be ordered

The fundamental functions of the set


ADT

Preliminary Definitions
A set is a collection of objects.
Set A is a subset of set B if all elements of A are in B.
Union of two sets A and B is a set C which consists of
all elements in A and B
Two sets are mutually disjoint if they do not have a
common element.

A partition of a set is a collection of subsets such that


Union of all these subsets is the set itself
Any two subsets are mutually disjoint
S = {1,2,3,4}, A = {1,2}, B = {3,4}, C = {2,3,4}, D = {4}
Is A, B a partition of S? Yes
Is A, C partition of S?

No

Is A, D partition of S?

No

Union and Find Operations


Operations on partitions.
Union
Need to form union of two different sets of a
partition
Find
Need to find out which set an element belongs to

A Set As A Tree
S = {2, 4, 5, 9, 11, 13, 30}
Some possible tree representations:

13
2

11

30

9
2

5
11

4
11

13
4

13

2
9

30
30

Result Of A Find Operation


find(i) is to identify the set that contains element i.
In most applications of the union-find problem, the user does

not provide set identifiers.


The requirement is that find(i) and find(j) return the same

value if elements i and j are in the same set.


4
2

11

30

13

find(i) will return the element that is in the tree root.

Strategy For find(i)


13
4
9

5
11

30

2
Start at the node that represents element i and climb up

the tree until the root is reached.


Return the element in the root.
To climb the tree, each node must have a parent pointer.

Trees With Parent Pointers


7

13
4
9

5
11

22

30

10

2
1

20

16

14

12

Possible Node Structure


Use nodes that have two fields: element and

parent.
Use an array table[] such that table[i] is a pointer to

the node whose element is i.


To do a find(i) operation, start at the node given by

table[i] and follow parent fields until a node whose


parent field is null is reached.
Return element in this root node.

Example

13
4
9

5
11

30

2
1
table[]
0

10

15

(Only some table entries are shown.)

Union Operation
union(i,j)
i and j are the roots of two different trees, i != j.

To unite the trees, make one tree a subtree of

the other.
parent[j] = i

Smart Union Strategies


7

13
4
9

5
11

22

30

2
1

10
20

16

14

union(7,13)
Which tree should become a subtree of the other?

12

Height Rule
Make tree with smaller height a subtree of the other

tree.
Break ties arbitrarily.

13
4
9

5
11

30

22

2
1

10

union(7,13)
20

16

14

12

Weight
Rule
Make tree with fewer number of elements a subtree of the other tree.
Break ties arbitrarily.

7
13
4
9

22

5
11

10

30

2
1

union(7,13)

20

16

14

12

Implementation
Root of each tree must record either its height or the

number of elements in the tree.


When a union is done using the height rule, the

height increases only when two trees of equal height


are united.
When the weight rule is used, the weight of the new

tree is the sum of the weights of the trees that are


united.

Height Of A Tree
Suppose we start with single element trees and

perform unions using either the height or the


weight rule.
The height of a tree with p elements is at most

floor (log2p) + 1.

Sprucing Up The Find Method


7
13
4
9

2
1

22

g 11

10

30
20

16

a, b, c, d, e, f, and g are subtrees

a b c
find(1)
Do additional work to make future finds easier.

14

12

Path Compaction
Make all nodes on find path point to tree root.
find(1)

7
13
4
9

2
1

22

g 11

10

30
20

a b c

16

a, b, c, d, e, f, and g are subtrees


Makes two passes up the tree.

14

12

Path Splitting
Nodes on find path point to former grandparent.
find(1)

7
13
4
9

2
1

22

g 11

10

30
20

a b c

16

a, b, c, d, e, f, and g are subtrees


Makes only one pass up the tree.

14

12

Path Halving

Parent pointer in every other node on find path is changed to former grandparent.
find(1)

7
13
4
9

2
1

22

g 11

10

30
20

a b c

a, b, c, d, e, f, and g are subtrees


Changes half as many pointers.

16

14

12

GRAPHS

Graphs
A graph is a way of representing relationships that

exist between pairs of objects.


A graph consists of a set of nodes (or vertices) and

a set of arcs (or edges)


Graph G = Nodes {A,B, C} Arcs {(A,C), (B,C)}

Terminology
V = Set of vertices (or nodes)
|V| = # of vertices or cardinality of V (in usual terminology |V| = n)
E = Set of edges, where an edge is defined by two vertices
|E| = # of edges or cardinality of E
A Graph, G is a pair

G = (V, E)

Labeled Graphs:
We may give edges and vertices labels.
Graphing applications often require the
labeling of vertices Edges might also be
numerically labeled. For instance if the
vertices represent cities, the edges might
be labeled to represent distances.

Graph Terminology
Directed (or digraph) & Undirected Graphs
A directed graph is one in which every edge (u,v) has a direction, so that
(u,v) is different from (v,u).
In an undirected graph, there is no distinction between (u,v) and (v,u).
There are two possible situations that can arise in a directed graph between

vertices u and v.

i) only one of (u,v) and (v,u) is present.


ii) both (u,v) and (v,u) are present.
An edge (u, v) is said to be directed from u
to v if the pair (u, v) is ordered with u
preceding v.

D
A

E.g. A Flight Route


An edge (u, v) is said to be undirected if the
pair (u, v) is not ordered
E.g. Road Map

B
D

Graph Terminology
Two vertices joined by an edge are called the end

vertices or endpoints of the edge.


If an edge is directed its first endpoint is called the

origin and the other is called the destination.


Two vertices are said to be adjacent if they are

endpoints of the same edge.

Graph Terminology
a

D
g

C
f

Graph Terminology
a

D
g

C
Vertices A and B
are endpoints of edge a

Graph Terminology
a

D
g

C
Vertex A is the
origin of edge a

Graph Terminology
a

D
g

C
Vertex B is the
destination of edge a

Graph Terminology
a

D
g

C
Vertices A and B are
adjacent as they are
endpoints of edge a

Graph Terminology
An edge is said to be incident on a vertex if the vertex is one

of the edges endpoints.


The outgoing edges of a vertex are the directed edges whose

origin is that vertex.


The incoming edges of a vertex are the directed edges

whose destination is that vertex.

Graph Terminology
a

X
g

W
f

Edge 'a' is incident on vertex V


Edge 'h' is incident on vertex Z
Edge 'g' is incident on vertex Y

Graph Terminology
a

X
g

W
f

The outgoing edges of vertex W


are the edges with vertex W as
origin {d, e, f}

Graph Terminology
a

X
g

W
f

The incoming edges of vertex X


are the edges with vertex X as
destination {b, e, g, i}

Graph Terminology
The degree of a vertex v, denoted deg(v), is the

number of incident edges of v.


The in-degree of a vertex v, denoted indeg(v) is the

number of incoming edges of v.


The out-degree of a vertex v, denoted outdeg(v) is

the number of outgoing edges of v.

Graph Terminology
a

X
g

W
f

The degree of vertex X


is the number of incident
edges on X.
deg(X) = ?

Graph Terminology
a

X
g

W
f

The degree of vertex X


is the number of incident
edges on X.
deg(X) = 5

Graph Terminology
a

X
g

W
f

The in-degree of vertex X


is the number of edges that
have vertex X as a destination.
indeg(X) = ?

Graph Terminology
a

X
g

W
f

The in-degree of vertex X


is the number of edges that
have vertex X as a destination.
indeg(X) = 4

Graph Terminology
a

X
g

W
f

The out-degree of vertex X


is the number of edges that
have vertex X as an origin.
outdeg(X) = ?

Graph Terminology
a

d
e

X
g

W
f

The out-degree of vertex X


is the number of edges that
have vertex X as an origin.
outdeg(X) = 1

Graph Terminology
Path:
Sequence of alternating vertices and edges
begins with a vertex
ends with a vertex
each edge is preceded and followed by its endpoints

Simple Path:
A path where all its edges and vertices are distinct

Graph Terminology
a

P1

X
g

W
f

h
i

We can see that P1 is


a simple path.
P1 = {U, a, V, b, X, h, Z}

Graph Terminology
a

X
g

W
f

P2 is not a simple path


as not all its edges and
vertices are distinct.
P2 = {U, c, W, e, X, g, Y, f, W, d, V}

Graph Terminology
Cycle:
Circular sequence of alternating vertices and

edges.
Each edge is preceded and followed by its

endpoints.
Simple Cycle:
A cycle such that all its vertices and edges are

unique.

Graph Terminology
a

W
f

Simple cycle
{U, a, V, b, X, g, Y, f, W, c}

Graph Terminology
a

W
f

Y
Non-Simple Cycle
{U, c, W, e, X, g, Y, f, W, d, V, a}

Graph Representations
Adjacency Matrix
Adjacency Lists

Adjacency Matrix
Let G=(V-vertices,E-edges) be a graph with n vertices.
The adjacency matrix of G is a two-dimensional
n by n array, say adj_mat
If the edge (vi, vj) is in E(G), adj_mat[i][j]=1
If there is no such edge in E(G), adj_mat[i][j]=0
The adjacency matrix for an undirected graph is
symmetric;
The adjacency matrix for a digraph need not be symmetric

Adjacency Matrix
1

4
5

Examples for Adjacency Matrix


0

1
0
1

1
0
1
1

1
1
0
1

G1

1
1
1

1
2

0 1 0

1
0
1

0 0 0

G2

symmetric
undirected: n2/2
directed: n2

2
3

0
1

0
0

0
0

1
0
0
1
0
0
0
0

1
0
0
1
0
0
0
0

0
1
1
0
0
0
0
0

0
0
0
0
0
1
0
0

G4

0
0
0
0
1
0
1
0

0
0
0
0
0
1
0
1

0
0
0

0
0

0
1

Adjacency Matrix

Array-based implementation

Merits of Adjacency Matrix


From

the adjacency matrix, to determine the

connection of vertices is easy


The degree of a vertex is

n 1

adj _ mat[i][ j ]
j 0

For a digraph (= directed graph), the row sum is the


out_degree, while the column sum is the in_degree
n 1

ind (vi ) A[ j , i ]
j 0

n 1

outd (vi ) A[i, j ]


j 0

Adjacency Lists
Representation

A graph of n nodes is represented by a one-dimensional

array L of linked lists, where


L[i] is the linked list containing all the nodes adjacent from

node i.
The nodes in the list L[i] are in no particular order

Graphs: Adjacency List


Adjacency list: for each vertex vV,

store a list of vertices adjacent to v


Example:

Adj[1] = {2,3}
Adj[2] = {3}
Adj[3] = {}

Adj[4] = {3}

Variation: can also keep a list of

edges coming into vertex

Adjacency Lists (data structures)


Each row in adjacency matrix is represented as an adjacency list.
0

0
1
2
3

1
0
0
0

2
2
1
1

1
0

2
G3

3
3
3
2
0

G1

0
1
2

1
2

0
1
2
3
4
5
6
7

1
0
0
1
5
4
5
6

2
3
3
2
6
7

G4

An undirected graph with n vertices and e edges ==> n head nodes and 2e list nodes

Adjacency List

Linked-list implementation

Reachability
Reachability: Given two vertices 'u' and 'v' of a directed graph G,

we say that 'u' reaches 'v' if G has a directed path from 'u' to 'v'.
That is 'v' is reachable from 'u'.
A directed graph is said to be strongly connected if for any two

vertices 'u' and 'v' of G, 'u' reaches 'v'.

Graph Traversal
Problem: Search for a certain node or traverse all

nodes in the graph


Depth First Search
Once a possible path is found, continue the search until the

end of the path


Breadth First Search
Start several paths at a time, and advance in each one

step at a time

Depth First Search

DFS follows the following rules:


1. Select an unvisited node x, visit it, and treat as the
2.
3.

4.
5.

current node
Find an unvisited neighbor of the current node, visit it,
and make it the new current node;
If the current node has no unvisited neighbors,
backtrack to the its parent, and make that parent the
new current node;
Repeat steps 3 and 4 until no more nodes can be
visited.
If there are still unvisited nodes, repeat from step 1.

Example
Start vertex: 0
Traverse order: 0, 1, 3, 7, 4, 5, 2, 6

0
2

1
3

4
7

Depth First Search


A

Unexplored Vertex

Visited Vertex

Unexplored Edge
Discovery Edge
Back Edge

Start At Vertex A

D
C

Discovery Edge

D
C

Visited Vertex B

Discovery Edge

D
C
Visited Vertex C

D
C
Back Edge

D
C
Discovery Edge

D
C
Visited Vertex D

D
C
Back Edge

D
C

Discovery Edge

D
C

E
Visited Vertex E

Discovery Edge

D
C

Breadth First Search

BFS follows the following rules:


1. Select an unvisited node x, visit it, have it be the root in a BFS

tree being formed. Its level is called the current level.


2. From each node z in the current level, in the order in which the

level nodes were visited, visit all the unvisited neighbors of z.


The newly visited nodes from this level form a new level that
becomes the next current level.
3. Repeat step 2 until no more nodes can be visited.
4. If there are still unvisited nodes, repeat from Step 1.

Example
Start vertex: 0
Traverse order: 0, 1, 2, 3, 4, 5, 6, 7

0
2

1
3

4
7

Start Vertex A
Create a sequence L0
insert(A) into L0

Start Vertex A
L0

while L0 is not empty


create a new empty list L1

Start Vertex A
L0

for each v in L0 do
get incident edges of v

Start Vertex A
L0

if first incident edge is unexplored


get opposite of v, say w
if w is unexplored
set edge as discovery

Start Vertex A
L0

L1

set vertex w as visited


and insert(w) into L1

Start Vertex A
L0

L1

get next incident edge

Start Vertex A
L0

L1

if edge is unexplored
we get vertex opposite v
say w,
if w is unexplored

Start Vertex A
L0

L1

if w is unexplored
set edge as discovery

Start Vertex A
L0

L1

set w as visited and


add w to L1

Start Vertex A
L0

L1

continue in this fashion


until we have visited all
incident edge of v

Start Vertex A
L0

L1

continue in this fashion


until we have visited all
incident edge of v

Start Vertex A
L0

L1

as L0 is now empty
we continue with list L1

Start Vertex A
L0

L1

as L0 is now empty
we continue with list L1

L2

Start Vertex A
L0

L1

L2

Start Vertex A
L0

L1

L2

Start Vertex A
L0

L1

L2

Start Vertex A
L0

L1

L2

Start Vertex A
L0

L1

L2

Start Vertex A
L0

L1

L2

Connected Component
Find all connected component in a graph G
Select one unvisited vertex v, and start DFS (or BFS) on v
Select one another unvisited vertex v, and start DFS (or BFS)

on v

Example
Start on 0
0, 1, 3, 4, 7 is visited

These 5 vertices is in the

component

same connected
3

Choose 2
2, 5, 6 is visited

DFS vs. BFS


DFS Process

start

destination

A DFS on A
G
D
B
A

B DFS on B
A

Call DFS on G

C
B
A

DFS on C

D
B
A

Call DFS on D
Return to call on B

found destination - done!


Path is implicitly stored in DFS recursion
Path is: A, B, D, G

DFS vs. BFS


F

G
destination

rear

front

BFS Process
rear

front

A
Initial call to BFS on A
Add A to queue
rear

rear

front

D C

Dequeue A
Add B

Dequeue B
Add C, D

start

front

G
Dequeue D
Add G

found destination - done!


Path must be stored separately

rear

front

D
Dequeue C
Nothing to add

Graph Applications
Some of the applications of graphs are :
Networks (computer, cities ....)
Maps (any geographic databases )
Graphics : Geometrical Objects
Neighborhood graphs
Flow Problem
Workflow

You might also like