Trees and Graphs ppt
Trees and Graphs ppt
Trees
• Basic Terminology,
• Binary Trees and their Representation,
• Complete Binary Trees, Binary Search Trees,
• Operations on Binary Trees (Insertion, Deletion, Search &
Traversal),
• Application: Expression Evaluation.
Graphs
• Terminology and Representations,
• Graphs & Multigraphs,
• Directed Graphs,
• Sequential Representation of Graphs,
• Adjacency Matrices, Graph Transversal,
• Connected Components and Spanning Trees.
Trees
• We read the linear data structures like an array, linked list, stack and queue in
which all the elements are arranged in a sequential manner. The different data
structures are used for different kinds of data.
• Some factors are considered for choosing the data structure:
• What type of data needs to be stored?: It might be a possibility that a certain
data structure can be the best fit for some kind of data.
• Cost of operations: If we want to minimize the cost for the operations for the
most frequently performed operations. For example, we have a simple list on
which we have to perform the search operation; then, we can create an array in
which elements are stored in sorted order to perform the binary search. The
binary search works very fast for the simple list as it divides the search space into
half.
• Memory usage: Sometimes, we want a data structure that utilizes less memory.
• A tree is also one of the data structures that represent hierarchical
data. Suppose we want to show the employees and their positions in
the hierarchical form then it can be represented as shown below:
•
• The above tree shows the organization hierarchy of some company.
In the above structure, john is the CEO of the company, and John has
two direct reports named as Steve and Rohan. Steve has three direct
reports named Lee, Bob, Ella where Steve is a manager. Bob has two
direct reports named Sal and Emma. Emma has two direct reports
named Tom and Raj. Tom has one direct report named Bill. This
particular logical structure is known as a Tree. Its structure is similar
to the real tree, so it is named a Tree. In this structure, the root is at
the top, and its branches are moving in a downward direction.
Therefore, we can say that the Tree data structure is an efficient way
of storing the data in a hierarchical way.
• Let's understand some key points of the Tree data structure.
• A tree data structure is defined as a collection of objects or entities known
as nodes that are linked together to represent or simulate hierarchy.
• A tree data structure is a non-linear data structure because it does not
store in a sequential manner. It is a hierarchical structure as elements in a
Tree are arranged in multiple levels.
• In the Tree data structure, the topmost node is known as a root node. Each
node contains some data, and data can be of any type. In the above tree
structure, the node contains the name of the employee, so the type of data
would be a string.
• Each node contains some data and the link or reference of other nodes
that can be called children.
Basic Terminology
Basic Terminology In Tree Data Structure:
• Parent Node: The node which is a predecessor of a node is called the
parent node of that node. {2} is the parent node of {6, 7}.
• Child Node: The node which is the immediate successor of a node is called
the child node of that node. Examples: {6, 7} are the child nodes of {2}.
• Root Node: The topmost node of a tree or the node which does not have
any parent node is called the root node. {1} is the root node of the tree. A
non-empty tree must contain exactly one root node.
• Degree of a Node: The total count of subtrees attached to that node is
called the degree of the node. The degree of a leaf node must be 0. The
degree of a tree is the degree of its root. The degree of the node {3} is 3.
• Leaf Node or External Node: The nodes which do not have any child nodes
are called leaf nodes. {6, 14, 8, 9, 15, 16, 4, 11, 12, 17, 18, 19} are the leaf
nodes of the tree.
• Ancestor of a Node: Any predecessor nodes on the path of the root to that
node are called Ancestors of that node. {1, 2} are the parent nodes of the
node {7}
• Descendant: Any successor node on the path from the leaf node to that
node. {7, 14} are the descendants of the node. {2}.
• Sibling: Children of the same parent node are called siblings. {8, 9, 10} are
called siblings.
• Depth of a node: The count of edges from the root to the node. Depth of
node {14} is 3.
• Height of a node: The number of edges on the longest path from that
node to a leaf. Height of node {3} is 2.
• Height of a tree: The height of a tree is the height of the root node i.e
the count of edges from the root to the deepest node. The height of
the above tree is 3.
• Level of a node: The count of edges on the path from the root node
to that node. The root node has level 0.
• Internal node: A node with at least one child is called Internal Node.
• Subtree: Any node of the tree along with its descendants
Implementation of Tree
• Storing naturally hierarchical data: Trees are used to store the data in
the hierarchical structure. For example, the file system. The file
system stored on the disc drive, the file and folder are in the form of
the naturally hierarchical data and stored in the form of trees.
• Organize data: It is used to organize data for efficient insertion,
deletion and searching.
• Routing table: The tree data structure is also used to store the data in
routing tables in the routers.
Types of Tree data structure
• General tree: The general tree is one of the types of tree data structure. In the general tree, a
node can have either 0 or maximum n number of nodes. There is no restriction imposed on the
degree of the node (the number of nodes that a node can contain). The topmost node in a
general tree is known as a root node. The children of the parent node are known as subtrees.
• There can be n number of subtrees in a general tree. In the general
tree, the subtrees are unordered as the nodes in the subtree cannot
be ordered.
Every non-empty tree has a downward edge, and these edges are
connected to the nodes known as child nodes. The root node is
labeled with level 0. The nodes that have the same parent are known
as siblings.
• Binary tree: Here, binary name itself suggests two numbers, i.e., 0
and 1. In a binary tree, each node in a tree can have utmost two child
nodes. Here, utmost means whether the node has 0 nodes, 1 node
or 2 nodes.
• Binary Search tree: Binary search tree is a non-linear data structure in
which one node is connected to n number of nodes. It is a node-
based data structure. A node can be represented in a binary search
tree with three fields, i.e., data part, left-child, and right-child. A node
can be connected to the utmost two child nodes in a binary search
tree, so the node contains two pointers (left child and right child
pointer).
Every node in the left subtree must contain a value less than the value
of the root node, and the value of each node in the right subtree
must be bigger than the value of the root node.
• A node can be created with the help of a user-defined data type known
as struct, as shown below:
struct node
{
int data;
struct node *left;
struct node *right;
}
The above is the node structure with three fields: data field, the second field
is the left pointer of the node type, and the third field is the right pointer of
the node type.
Binary Tree
• The Binary tree means that the node can have maximum two
children. Here, binary name itself suggests that 'two'; therefore, each
node can have either 0, 1 or 2 children.
• The above tree is a binary tree because each node contains the
utmost two children. The logical representation of the above tree is
given below:
•
• In the above tree, node 1 contains two pointers, i.e., left and a right
pointer pointing to the left and right node respectively. The node 2
contains both the nodes (left and right node); therefore, it has two
pointers (left and right). The nodes 3, 5 and 6 are the leaf nodes, so
all these nodes contain NULL pointer on both left and right parts.
Properties of Binary Tree
• A Binary tree is implemented with the help of pointers. The first node in
the tree is represented by the root pointer. Each node in the tree consists
of three parts, i.e., data, left pointer and right pointer. To create a binary
tree, we first need to create the node. We will create the node of user-
defined as shown below:
struct node
{
int data,
struct node *left, *right;
}
In the above structure, data is the value, left pointer contains the address of
the left node, and right pointer contains the address of the right node.
Binary Tree program in C
#include<stdio.h>
struct node
{
int data;
struct node *left, *right;
};
void main()
{
struct node *root;
root = create();
}
struct node *create()
{
struct node *temp;
int data;
temp = (struct node *)malloc(sizeof(struct node));
printf("Press 0 to exit");
printf("\nPress 1 for new node");
printf("Enter your choice : ");
scanf("%d", &choice);
if(choice==0)
{
return 0;
}
else
{
printf("Enter the data:");
scanf("%d", &data);
temp->data = data;
printf("Enter the left child of %d", data);
temp->left = create();
printf("Enter the right child of %d", data);
temp->right = create();
return temp;
}
}
• The above code is calling the create() function recursively and
creating new node on each recursive call. When all the nodes are
created, then it forms a binary tree structure. The process of visiting
the nodes is known as tree traversal. There are three types traversals
used to visit a node:
• Inorder traversal
• Preorder traversal
• Postorder traversal
Binary Search Tree
SN Operation Description
1 Searching in BST Finding the location of some specific element in a
binary search tree.
#include<stdio.h>
#include<stdlib.h>
void insert(int);
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *root;
void main ()
{
int choice,item;
do
{
printf("\nEnter the item which you want to insert?\n");
scanf("%d",&item);
insert(item);
printf("\nPress 0 to insert more ?\n");
scanf("%d",&choice);
}while(choice == 0);
}
void insert(int item)
{
struct node *ptr, *parentptr , *nodeptr;
ptr = (struct node *) malloc(sizeof (struct node));
if(ptr == NULL)
{
printf("can't insert");
}
else
{
ptr -> data = item;
ptr -> left = NULL;
ptr -> right = NULL;
if(root == NULL)
{
root = ptr;
root -> left = NULL;
root -> right = NULL;
}
else
{
parentptr = NULL;
nodeptr = root;
while(nodeptr != NULL)
{
parentptr = nodeptr;
if(item < nodeptr->data)
{
nodeptr = nodeptr -> left;
}
else
{
nodeptr = nodeptr -> right;
}
}
if(item < parentptr -> data)
{
parentptr -> left = ptr;
}
else
{
parentptr -> right = ptr;
}
}
printf("Node Inserted");
}
}
Deletion
• It is the simplest case, in this case, replace the leaf node with the
NULL and simple free the allocated space.
• In the following image, we are deleting the node 85, since the node is
a leaf node, therefore the node will be replaced with NULL and
allocated space will be freed.
The node to be deleted has only one child.
• In this case, replace the node with its child and delete the child node,
which now contains the value which is to be deleted. Simply replace it
with the NULL and free the allocated space.
• In the following image, the node 12 is to be deleted. It has only one
child. The node will be replaced with its child node and the replaced
node 12 (which is now leaf node) will simply be deleted.
The node to be deleted has two children.
• After visiting node B, we move to the right child of node B, i.e., D. Since
node D is a leaf node, so node D gets printed as shown below:
• The left part of node A is traversed. Now, we will visit the root node,
i.e., A, and it gets printed as shown below:
• Once the traversing of left part and root node is completed, we move
to the right part of the root node. We move to the right child of node
A, i.e., C. The node C has also left child, i.e., E and E has also left child,
i.e., G. Since G is a leaf node, so G gets printed as shown below:
The root node of G is E, so it gets printed as shown below
Since E does not have any right child, so we move to the root of
the E node, i.e., C. C gets printed as shown below:
Once the left part of node C and the root node, i.e., C, are
traversed, we move to the right part of Node C. We move to
the node F and node F has a left child, i.e., H. Since H is a leaf
node, so it gets printed as shown below:
• Now we move to the root node of H, i.e., F and it gets printed as
shown below:
• After visiting the F node, we move to the right child of node F, i.e., I,
and it gets printed as shown below:
• Since node B does not have a left child, and it has only a right child;
therefore, D gets printed as shown below:
• Once the left part of the root node A is traversed, we move to the
right part of node A. The right child of node A is C. Since C is a root
node for all the other nodes; therefore, C gets printed as shown
below:
Once the left part and the right part of node C are traversed,
then the node C is traversed as shown below:
• In the above tree, the left subtree and the right subtree of root node
A have been traversed, the node A would be traversed.
Tress Traversal
OUTPUT
• Inorder traversal
• 8 ->9 ->7 ->10 ->11 ->12 ->13 ->
• Preorder traversal
• 10 ->9 ->8 ->7 ->12 ->11 ->13 ->
• Postorder traversal
• 8 ->7 ->9 ->11 ->13 ->12 ->10 ->
Application: Expression Evaluation.
• Expression Tree
• The expression tree is a binary tree in which each internal node
corresponds to the operator and each leaf node corresponds to the
operand so for example expression tree for 3 + ((5+9)*2) would be:
•
• Inorder traversal of expression tree produces infix version of given
postfix expression (same with postorder traversal it gives postfix
expression)
Construction of Expression Tree:
• Now For constructing an expression tree we use a stack. We loop
through input expression and do the following for every character.
1.If a character is an operand push that into the stack
2.If a character is an operator pop two values from the stack make
them its child and push the current node again.
• In the end, the only element of the stack will be the root of an
expression tree.
Evaluation of Expression Tree
Output :
110
• As all the operators in the tree are binary hence each node will have
either 0 or 2 children. As it can be inferred from the examples above,
the integer values would appear at the leaf nodes, while the interior
nodes represent the operators.
Graph
• A graph can be defined as group of vertices and edges that are used
to connect these vertices. A graph can be seen as a cyclic tree, where
the vertices (Nodes) maintain any complex relationship among them
instead of having parent child relationship.
Definition
• Path
A path can be defined as the sequence of nodes that are followed in order to reach
some terminal node V from the initial node U.
• Closed Path
• A path will be called as closed path if the initial node is same as terminal node. A path
will be closed path if V0=VN.
• Simple Path
• If all the nodes of the graph are distinct with an exception V0=VN, then such path P is
called as closed simple path.
• Cycle
• A cycle can be defined as the path which has no repeated edges or vertices except the
first and last vertices.
.
• Connected Graph
• A connected graph is the one in which some path exists between
every two vertices (u, v) in V. There are no isolated nodes in
connected graph.
• Complete Graph
• A complete graph is the one in which every node is connected with all
other nodes. A complete graph contain n(n-1)/2 edges where n is the
number of nodes in the graph
• Weighted Graph
• In a weighted graph, each edge is assigned with some data such as length
or weight. The weight of an edge e can be given as w(e) which must be a
positive (+) value indicating the cost of traversing the edge.
• Digraph
• A digraph is a directed graph in which each edge of the graph is associated
with some direction and the traversing can be done only in the specified
direction.
• Loop
• An edge that is associated with the similar end points can be called as
Loop.
• Adjacent Nodes
• If two nodes u and v are connected via an edge e, then the nodes u
and v are called as neighbours or adjacent nodes.
• The techniques by using which, we can traverse all the vertices of the
graph.
• Traversing the graph means examining all the nodes and vertices of
the graph. There are two standard methods by using which, we can
traverse the graphs. Lets discuss each one of them in detail.
• Breadth First Search
• Depth First Search
Breadth First Search (BFS) Algorithm
• Depth first search (DFS) algorithm starts with the initial node of the
graph G, and then goes to deeper and deeper until we find the goal
node or the node which has no children. The algorithm, then
backtracks from the dead end towards the most recent node that is
yet to be completely unexplored.
• The data structure which is being used in DFS is stack. The process is
similar to BFS algorithm. In DFS, the edges that leads to an unvisited
node are called discovery edges while the edges that leads to an
already visited node are called block edges.
C Program for Depth First Search
#include<stdio.h>
void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is
sorted in array G[10][10]
void main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
//visited is initialized to zero
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}
Connected Component Definition
• A connected component or simply component of an
undirected graph is a subgraph in which each pair of nodes is
connected with each other via a path.
• Let’s try to simplify it further, though. A set of nodes forms a
connected component in an undirected graph if any node
from the set of nodes can reach any other node by traversing
edges. The main point here is reachability.
• In connected components, all the nodes are always
reachable from each other.
One Connected Component
• Let’s name this graph G1(V, E). Here V = \{V1, V2, V3, V4, V5, V6\} denotes the vertex set
and E = \{E1, E2, E3, E4, E5, E6, E7\} denotes the edge set of G1. The graph G1 has one
connected component, let’s name it C1, which contains all the vertices of G1. Now let’s
check whether the set C1 holds to the definition or not.
• According to the definition, the vertices in the set C1 should reach one another via a
path. We’re choosing two random vertices V1 and V6:
• Now, let’s see whether connected components C1, C2, and C3 satisfy the definition or not. We’ll
randomly pick a pair from each C1, C2, and C3 set.
• From the set C1, let’s pick the vertices V4 and V6.
• n this topic, we will learn about the spanning tree and minimum spanning tree. Before
knowing about the spanning trees, we should know about some graphs.
• The following are the types of graphs:
• Undirected graph: An undirected graph is a graph in which all the edges do not point to
any particular direction, i.e., they are not unidirectional; they are bidirectional.
It can also be defined as a graph in which set of V vertices and set of E edges, each edge
connecting two different vertices.
• Connected graph: A connected graph is a graph in which a path always exists from a
vertex to any other vertex.
A graph is connected if we can reach any vertex from any other vertex by following edges
in either direction.
• Directed graph: A directed graph is defined as a graph in which set of V vertices and set
of Edges, each connecting two different vertices, but it is not mandatory that node points
in the opposite direction also.
What is a Spanning tree?
• The minimum spanning tree is the tree whose sum of the edge
weights is minimum. From the above spanning trees, the total edge
weight of the spanning tree 1 is 12, the total edge weight of the
spanning tree 2 is 14, and the total edge weight of the spanning tree
3 is 11; therefore, the total edge weight of the spanning tree 3 is
minimum. From the above graph, we can also create one more
spanning tree as shown below:
In the above tree, the total edge weight is 10 which is less than
the above spanning trees; therefore, the minimum spanning
tree is a tree which is having an edge weight, i.e., 10.
Properties of Spanning tree
• A connected graph can contain more than one spanning tree. The
spanning trees which are minimally connected or we can say that the
tree which is having a minimum total edge weight would be
considered as the minimum spanning tree.
• All the possible spanning trees that can be created from the given
graph G would have the same number of vertices, but the number of
edges in the spanning tree would be equal to the number of vertices
in the given graph minus 1.
• The spanning tree does not contain any cycle. Let's understand this
property through an example.
• Suppose we have the graph which is given below: