You are on page 1of 60

UNIT IV

UNIT IV : Trees, Binary Trees,


Representation of binary trees in memory,
Traversing Binary Trees- Pre order, In-order,
Post order, Graphs, Multi graphs, directed
graphs, Adjacency matrix, path matrix,
Traversing a graph, Breadth first search,
Depth first search.
Trees
Tree is a non-linear data structure which organizes data in
hierarchical structure and this is a recursive definition.
In tree data structure, every individual element is called as
Node. Node in a tree data structure, stores the actual data of
that particular element and link to next element in hierarchical
structure.
In a tree data structure, if we have N number of nodes then we
can have a maximum of N-1 number of links(edges).
Terminology
In a tree data structure, we use the following terminology...

1. Root
In a tree data structure, the first node is called as Root Node. Every
tree must have root node. We can say that root node is the origin of
tree data structure. In any tree, there must be only one root node.
We never have multiple root nodes in a tree.
2. Edge
In a tree data structure, the connecting link between any two nodes
is called as EDGE. In a tree with 'N' number of nodes there will be a
maximum of 'N-1' number of edges.
3. Parent
In a tree data structure, the node which is predecessor of any node is
called as PARENT NODE. In simple words, the node which has branch
from it to any other node is called as parent node. Parent node can also
be defined as "The node which has child / children".
4. Child
In a tree data structure, the node which is descendant of any node is called
as CHILD Node. In simple words, the node which has a link from its parent
node is called as child node. In a tree, any parent node can have any
number of child nodes. In a tree, all the nodes except root are child nodes.
5. Siblings
 In a tree data structure, nodes which belong to same
Parent are called as SIBLINGS.
 In simple words, the nodes with same parent are called
as Sibling nodes.
6. Leaf
 In a tree data structure, the node which does not have a child is
called as LEAF Node.
 In simple words, a leaf is a node with no child.
 In a tree data structure, the leaf nodes are also called as External
Nodes.
 External node is also a node with no child. In a tree, leaf node is
also called as 'Terminal' node.
7. Internal Nodes
 In a tree data structure, the node which has at least one child
is called as INTERNAL Node.
 In simple words, an internal node is a node with at least one
child.
 In a tree data structure, nodes other than leaf nodes are
called as Internal Nodes.
 The root node is also said to be Internal Node if the tree has
more than one node.
 Internal nodes are also called as 'Non-Terminal' nodes.
8. Degree
In a tree data structure, the total number of children of a node is called as
DEGREE of that Node. In simple words, the Degree of a node is total
number of children it has. The highest degree of a node among all the
nodes in a tree is called as 'Degree of Tree'
9. Level
In a tree data structure, the root node is said to be at Level 0 and the
children of root node are at Level 1 and the children of the nodes
which are at Level 1 will be at Level 2 and so on... In simple words, in
a tree each step from top to bottom is called as a Level and the Level
count starts with '0' and incremented by one at each level (Step).
10. Height
In a tree data structure, the total number of edges from leaf node to a
particular node in the longest path is called as HEIGHT of that Node. In a
tree, height of the root node is said to be height of the tree. In a tree,
height of all leaf nodes is '0'.
11. Depth
In a tree data structure, the total number of egdes from root node to a
particular node is called as DEPTH of that Node. In a tree, the total
number of edges from root node to a leaf node in the longest path is said
to be Depth of the tree. In simple words, the highest depth of any leaf
node in a tree is said to be depth of that tree. In a tree, depth of the root
node is '0'.
12. Path
In a tree data structure, the sequence of Nodes and Edges from one
node to another node is called as PATH between that two Nodes.
Length of a Path is total number of nodes in that path. In below
example the path A - B - E - J has length 4.
13. Sub Tree
In a tree data structure, each child from a node forms a subtree
recursively. Every child node will form a subtree on its parent node.
Binary Tree

 Binary tree is a special type of tree data structure in


which every node can have a maximum of 2 children.
 One is known as left child and the other is known as
right child.
 In a binary tree, every node can have either 0 children
or 1 child or 2 children but not more than 2 children.
Binary Tree Representations

 Here we will see how to represent a binary tree in

computers memory. There are two different methods for

representing.

 These are using array and using linked list.


Suppose we have one tree like this −
1.Array Representation
The array representation stores the tree data by scanning
elements using level order fashion. So it stores nodes level by
level. If some element is missing, it left blank spaces for it. The
representation of the above tree is like below −

The index 1 is holding the root, it has two children 50 and 21, they
are placed at location 2 and 3. Some children are missing, so their
place is left as blank.
2. Linked List Representation

In this representation, we use two types of nodes one for

representing the node with data and another for representing only

references. We start with a node with data from root node in the

tree. Then it is linked to an internal node through a reference node

and is linked to any other node directly. This process repeats for all

the nodes in the tree.


We create node for each element. This will be look like below −
Binary Tree Traversals

 In any binary tree displaying order of nodes depends on

the traversal method.

 Displaying (or) visiting order of nodes in a binary tree is

called as Binary Tree Traversal.

There are three types of binary tree traversals.

1. In - Order Traversal

2. Pre - Order Traversal

3. Post - Order Traversal


 3 main methods for tree traversal

 Inorder Traversal (left, root, right)

 Preorder Traversal (root, left, right)

 Postorder Traversal (left, right, root)

 use the recursive function while traversing the tree and call

the function again and again until we will traverse all the

nodes of the tree.


Inorder Tree Traversal

Using the inorder traversal method, first visit the left subtree of

the original tree. Then we will traverse the root node of the tree

and lastly the right subtree of the original tree.


Algorithm for Inorder Tree Traversal
1. Calling Inorder (left-subtree)
2. Visit the root node
3. Calling Inorder (right subtree)
Inorder Tree Traversal

The result in the array as shown below.


1. In-order Traversal – L N R
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.

In-Order Traversal for above example of binary tree is I - I I


-D-J-B-F-A-G-K-C-H
2. Pre-Order Traversal N L R
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree

Pre-Order Traversal for above example binary tree is


A-B-D-I-J-F-C-G-K-H
3. Post-order Traversal L R N
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.

Post-Order Traversal for above example binary tree is


I-J-D-F-B-K-G-H-C–A
Definition - Graph

A graph G can be defined as an ordered set G(V, E) where V(G)

represents the set of vertices and E(G) represents the set of edges which

are used to connect these vertices.

There are three types of Graph . 

1. Directed Graph

2. Undirected Graph

3. WeightedGraph
A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C),
(C,E), (E,D), (D,B), (D,A)) is shown in the following figure.
Graph Representation

By Graph representation, we simply mean the

technique which is to be used in order to store

some graph into the computer's memory.

The two most common representation of the graphs are:

 Adjacency Matrix

 Adjacency List
Adjacency Matrix Representation

If an Undirected Graph G consists of n vertices then the adjacency

matrix of a graph is n x n matrix A = [aij] and defined by -

aij = 1 {if there is a path exists from Vi to Vj}

aij = 0 {Otherwise}

The adjacency matrix, also called the connection matrix


  1. Adjacency matrix for an undirected graph Representation
AIn an undirected graph, edges are not associated with the
directions with them. In an undirected graph, if there is an edge
exists between Vertex A and Vertex B, then the vertices can be
transferred from A to B as well as B to A.
Adjacency matrix for a directed graph
In a directed graph, edges form an ordered pair. Edges
represent a specific path from some vertex A to another vertex
B.
Adjacency matrix for a weighted directed graph
Question 1 - What will be the adjacency matrix for the
below undirected weighted graph?
Question 2 - What will be the adjacency matrix for the
below directed weighted graph?
2. Linked list representation/ adjacency list

representation

 An adjacency list is used in the linked representation to

store the Graph in the computer's memory.

 It is efficient in terms of storage as we only have to store

the values for edges.


Let's see the adjacency list representation of an

undirected graph.
Let's see the adjacency list representation of an

directed graph.
Let's see the adjacency list representation of a

weighted directed graph.


Graph Traversal

Traversing the graph means examining/ Visiting all the nodes and

vertices of the graph.

There are two standard methods by using which, we can traverse the

graphs.

 Breadth First Search

 Depth First Search


What is BFS?

BFS stands for Breadth First Search.

It is also known as level order traversal.


Breadth-First Search Algorithm
 BFS is a graph traversal approach in which you start at a source
node and layer by layer through the graph, analyzing the nodes
directly related to the source node. Then, in BFS traversal, you
must move on to the next-level neighbor nodes.
 According to the BFS, you must traverse the graph in a
breadthwise direction:
 To begin, move horizontally and visit all the current layer's
nodes.
 Continue to the next layer.
Breadth-First Search Algorithm
 Assign ‘a’ as the root node and insert it into the Queue.
 Extract node ‘a’ from the queue and insert the child nodes of
‘a’, i.e., ‘b’ and ‘c’.
 Print node ‘a’.
 The queue is not empty and has node ‘b’ and ‘c’. Since ‘b’ is the
first node in the queue, let’s extract it and insert the child nodes
of ‘b’, i.e., node ‘d’ and ‘e’.
 Repeat these steps until the queue gets empty. Note that the
nodes that are already visited should not be added to the queue
again.
Breadth-First Search Algorithm
Breadth-First Search Algorithm Pseudocode
Input: s as the source node
BFS (G, s)
let Q be queue.
Q.enqueue( s )
mark s as visited
while ( Q is not empty)
v = Q.dequeue( )
for all neighbors w of v in Graph G
if w is not visited
Q.enqueue( w )
mark w as visited
Output:

Following is Breadth First Traversal (starting from vertex A)

ABCDEFG
Applications of BFS Algorithm
Let’s take a look at some of the real-life applications where a BFS algorithm
implementation can be highly effective.
Travelling Salesman Problem: BFS algorithm can easily create the shortest path of
the graph in the shortest time possible with high accuracy.
P2P Networks: BFS can be implemented to locate all the nearest or neighboring
nodes in a peer to peer network. This will find the required data faster.
Web Crawlers: Search engines or web crawlers can easily build multiple levels of
indexes by employing BFS. BFS implementation starts from the source, which is the
web page, and then it visits all the links from that source.
Navigation Systems: BFS can help find all the neighboring locations from the main
or source location.
Network Broadcasting: A broadcasted packet is guided by the BFS algorithm to find
and reach all the nodes it has the address for.
Applications of BFS Algorithm

Social Networking Websites: In social networks, we can find

people within a given distance ‘k’ from a person using Breadth

First Search till ‘k’ levels.

GPS Navigation systems: Breadth First Search is used to find all

neighboring locations.

Broadcasting in Network: In networks, a broadcasted packet

follows Breadth First Search to reach all nodes.

In Garbage Collection: Breadth First Search is used in copying

garbage collection using Cheney’s algorithm.


• BREADTH FIRST SEARCH
Queue front

Order of
Traversal A B D E C G F H I Queue rear
Depth-first search algorithm
 Depth-first search is an algorithm for traversing or searching tree
or graph data structures.
 The algorithm starts at the root node (selecting some arbitrary
node as the root node in the case of a graph) and explores as far as
possible along each branch before backtracking.
 So the basic idea is to start from the root or any arbitrary node and
mark the node and move to the adjacent unmarked node and
continue this loop until there is no unmarked adjacent node.
 Then backtrack and check for other unmarked nodes and traverse
them. Finally, print the nodes in the path.
Algorithm of DFS Algorithm
Given Input: Adjacency list of the given graph.
Procedure:

Step 1: Algorithm DFS(vertex v)


Step 2: visited[v] = 1

Step 3: for all nodes ‘w’ adjacent to v:


if(visited[w] == 0):
DFS(w)

Step 4: End for loop


Step 5: End DFS
• DFS

Order of
A B C F E G D H I Stack
Traversal
Applications of Depth-first search
Depth-first search is used in
topological sorting,
scheduling problems,

cycle detection in graphs


 solving puzzles with only one solution, such as a maze or a
sudoku puzzle.
 analyzing networks.

You might also like