DSU Unit 5 Notes Complete
DSU Unit 5 Notes Complete
Definition of a Tree : - A tree is a finite set of one or more nodes such that -
a. There is a specially designated node called root.
b. The remaining nodes are partitioned into n > = 0 disjoint sets T1 to Tn where each of those sets is a tree. T1 to Tn
are called the sub trees of the root.
Tree Terminology :-
1. Root: the first node is called as Root Node. In any tree, there must be only one root node. this node does not
have any parent.
2. Null Tree: A tree with no nodes is a Null Tree.
3. Node: 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. A node of a tree is an
item of information along with the branches to other nodes.
4. Parent Node: the node which is predecessor of any node is called as parent node. In simple words, The node
having further sub-branches is called parent node.
5. Child Node: When a predecessor of a node is parent then all successor nodes are called child nodes. In a tree
data structure, the node which is descendant of any node is called as child Node.
6. Leaf Node/Terminal Node: In a tree data structure, the node which does not have a child is called as leaf node.
Leaf node is a terminal node of a tree.
7. Siblings: In a tree data structure, nodes which belong to same Parent are called as siblings
Types of Trees : -
The different types of trees are :
1) General tree
2) Binary tree
3) Binary search tree
4) Strictly binary tree
5) Complete binary tree
6) Skewed binary tree
1) General tree : -
In a general tree, number of children per node is not limited to two.
There is NO fixed structure of a general tree.
Since, the number of children per node can vary greatly; it might not be feasible to make the children direct
links in the node.
Children of a node can be stored in a linked list with parent node storing the address of its leftmost child. And
left most child store address of all childs.
Example : Some nodes may have 1 or no sub-trees. The others may have 3 or 4 sub-trees.
Representation of Trees: -
Array [Sequential/ Static] Implementation of Tree : -
Rules: -
1. If ‘n’ is the number of nodes in the tree.
2. starting from the zero Level where the root is present. The root node is stored in the first memory location as
the first element in the array.
3. Its left child is stored at index 2i + 1. if 2i+1 < n, and If 2i+1 > n, then i has no left child.
4. Right child is stored at index 2i+2, if 2i+2<n, If (2i + 2) > n, then i has no right child.
5. To find the parent node of any ith node use i/2. if i≠1,
6. if i=1 then it is root node.
[Very Imp – when you calculate the left and right child then take ‘i=index value’, and when calculating the
parent of any node then take ‘i=node number’.]
e.g
Here, the number of levels is 3. Therefore, we need an array of size 23 -1=7 elements. The array representation as
shown after applying the rules :
struct node
{
int data;
struct node *left;
struct node *right;
};
Traversal
Types
In - Pre - Post -
Order Order Order
In - Order Traversal ( leftChild - root - rightChild ):-
• In order traversal is also called as symmetric traversal.
• This can be defined as follows:
• 1. Traverse the left sub-tree of root node in in-order.
• 2. Visit the root node.
• 3. Traverse the right sub-tree of root node in in-order.
Algorithm:
Step 1 : Repeat step 2 to 4
Step 2 : while tree! =NULL.
Step 3 : INORDER (TREE->LEFT)
Step 4 : Write "Tree ->Data"
Step 5: INORDER (Tree->Right)
[END of while]
Step 6 : END
Algorithm :
Step 1 : Repeat step 2 to 4
Step 2 : while tree!=NULL.
Step 3 : Write "Tree ->Data"
Step 4 : Preorder (Tree->Left)
Step 5 : Preorder (Tree->Right)
[END of while]
Step 6 : END.
void preorder(struct node *root)
{
if( root != NULL)
{
printf("%d ",root->data);
preorder(root->left); //recursive function call
preorder(root->right);
}
}
Post - Order Traversal ( leftChild - rightChild - root ) : -
• In Post-Order traversal, the root node is visited after left child and right child.
• This traversal is defined as follows:
1. Traverse the left child (sub-tree) of root node in post-order.
2. Traverse the right child (sub-tree) of root node in post-order.
3. Visit the root 'node'.
int main()
{
struct node *root = NULL;
int choice, item, n, i;
else
{
int top = 1;
while ( top >= 1 )
{
Unit.5-Trees & Graphs. A.S.Ahmad.Lect.Gov Poly, Dhule. Page 10
// Move to the left subtree if present and not visited
if(root->left != NULL && !stack[top].vleft)
{
stack[top].vleft = 1;
stack[top++].nodel = root;
root = root->left;
continue;
}
// Move to the right subtree if present and not visited
Menu driven program for binary search tree creation and tree traversing.
[Recursive]
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *right;
struct node *left;
};
• In order to create a binary search tree on given data use following steps:
• Step l Read a data in item variable.
• Step 2 Allocate memory for a new node and store the address in pointer root.
• Step 3 Store the data x in the node root.
• Step 4 If(data<root.data).
• Step 5 Recursively create the left subtree of root and make it the left child of root.
• Step 6 If(data>root.data).
• Step 7 Recursively create the right subtree of root and make it the right child of root.
if(current == NULL) {
parent->leftChild = tempNode;
Unit.5-Trees & Graphs. A.S.Ahmad.Lect.Gov Poly, Dhule. Page 16
return;
}
} //go to right of the tree
else {
current = current->rightChild;
[For deleting the node having 2 childs then we can take either the inorder successor OR the inorder predecessor
to be placed at the deleting node.]
Step 3: Swap both deleting node and node which found in above step.
Step 4: Then, check whether deleting node came to case 1 or case 2 else goto steps 2
Step 5: If it comes to case 1, then delete using case 1 logic.
Step 6: If it comes to case 2, then delete using case 2 logic.
Step 7: Repeat the same process until node is deleted from the tree.
Expression Tree : -
An expression tree is a representation of expressions arranged in a tree-like data structure.
Expression tree is a binary tree in which each internal node represent operator and each leaf node represent
operand.
The in-order traversal of expression tree gives you INFIX form of expression tree is : 3 + 5+9*2.
The pre-order traversal of expression tree gives you PREFIX form of expression tree is : +3 *+592.
The post-order traversal of expression tree gives you POSTFIX form of expression tree is : 359+2*+.
When we apply in-order traversal on given expression tree we will get INFIX expression: 4+2*3.
When we apply pre-order traversal on given expression tree we will get PREFIX expression: *+423.
When we apply post-order traversal on given expression tree we will get POST FIX expression: 42+3*.
Example 1: Let consider the expression tree in Fig. 5.51 and evaluate the expression and give the infix, prefix
and postfix expression.
Example 2: Let consider the following expression tree and evaluate the expression and give the infix, prefix and postfix
expression.
Example
The above is a graph with 5 vertices and 6 edges.
This graph G can be defined as G = ( V , E )
Where V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.
Application of Graphs :
It is used to describe a wide variety of relationships between objects.
For example the following information can be represented by graphs :
Family trees in which the member nodes have an edge from parent to each of their children.
Transportation networks in which nodes are airports, intersections, ports etc. The edges can be airline
flights, one-way roads, shipping routes etc.
Graph Terminology : -
Vertex : -
A individual data element of a graph is called as Vertex. Vertex is also known as node. In above example graph,
A, B, C, D & E are known as vertices.
Edge : -
An edge is a connecting link between two vertices. Edge is also known as Arc. An edge is represented as
(startingVertex, endingVertex). For example, in above graph, the link between vertices A and B is represented as
(A,B). In above example graph, there are 7 edges (i.e., (A,B), (A,C), (A,D), (B,D), (B,E), (C,D), (D,E)).
Types of
Edges
1. Undirected Edge - An undirected egde is a bidirectional edge. If there is a undirected edge between vertices A and B
then edge (A , B) is equal to edge (B , A).
4. Undirected Graph : -A graph with only undirected edges is said to be undirected graph.
5. Directed Graph : - A graph with only directed edges is said to be directed graph.
6. Mixed Graph : -A graph with undirected and directed edges is said to be mixed graph.
7. End vertices or Endpoints : - The two vertices joined by an edge are called the end vertices (or endpoints) of the
edge.
8. Origin : - If an edge is directed, its first endpoint is said to be origin of it.
9. Destination : -If an edge is directed, its first endpoint is said to be origin of it and the other endpoint is said to be the
destination of the edge.
10. Adjacent : - If there is an edge between vertices A and B then both A and B are said to be adjacent.
11. Incident : - An edge is said to be incident on a vertex if the vertex is one of the endpoints of that edge.
12. Outgoing Edge : - A directed edge is said to be outgoing edge on its orign vertex.
13. Incoming Edge : - A directed edge is said to be incoming edge on its destination vertex.
14. Degree : - Total number of edges connected to a vertex is said to be degree of that vertex.
15. Indegree : - Total number of incoming edges connected to a vertex is said to be indegree of that vertex.
16. Outdegree : - Total number of outgoing edges connected to a vertex is said to be outdegree of that vertex.
17. Parallel edges or Multiple edges : - If there are two undirected edges to have the same end vertices, and for two
directed edges to have the same origin and the same destination. Such edges are called parallel edges or multiple
edges.
18. Self-loop : - An edge (undirected or directed) is a self-loop if its two endpoints coincide.
19. Simple Graph : - A graph is said to be simple if there are no parallel and self-loop edges.
20. Path : - A path is a sequence of alternating vertices and edges that starts at a vertex and ends at a vertex such that
each edge is incident to its predecessor and successor vertex.
Graph Representations
Graph data structure is represented using following representations...
1. Adjacency Matrix. [Sequential Representation.]
2. Adjacency List. [Linked Representation.]
Assume : -
G Graph
V Set of Vertices
(i,j) Edge connecting Vi and Vj
A[i,j] Adjacency matrix element
i,j Vertices
#include <stdio.h>
#define MAX 10
void degree(int adj[][MAX],int x,int n)
{
int i,incount=0, outcount =0;
for(i=0;i<n;i++)
{
if( adj[x][i] ==1)
outcount++;
if( adj[i][x] ==l)
incount++;
}
printf( The indegree of the node %d is %d\n",x, incount++);
printf("The outdegree of the node %d is %d\n",x,outcount++);
}
int main()
{
int adj[MAX][MAX],n,I,j;
setbuf(stdout, NULL);
printf("Enter the total number of nodes in graph");
scanf("%d\&n);
for(i=0;i<n; i++)
for(j=0;j<n; j++)
{
For Directed graph, In this representation, every vertex of graph contains list of its adjacent vertices.
Example 2: Consider the weighted undirected graph in Fig and provide adjacency list.
Ans : -
Example4: Create an adjacency matrix and adjacency list for the weighted graph shown in fig.
Ans : -
(i) Adjacency Matrix:
A B C D E F
A 0 62 345 0 0 0
B 62 30 200 548 0 0
C 34
3 20 0 360 467 0
D 50 54
0 360 0 245 320
E 0 80 467 245 0 555
F 0 0 0 320 555 0
(ii) Adjacency List:
Algorithm:
Step 1 : Initialize all the vertices.
Step 2 : Push starting vertex onto the Stack.
Step 3 : Repeat Steps 4 and 5 until Stack is empty.
Step 4 : Push onto stack any adjacent NON-visited vertex of the current vertex.
Step 5 : if there is no such vertex then pop the top vertex from the stack and go to step 4.
Step 6 : Exit.
Algorithm:
Step 1 : Initialize all the vertices and create adjacent list.
Step 2 : Put Starting vertex in Queue.
Step 3 : Repeat Step 4 and 5 until Queue is empty.
Step 4 : Remove front node from the Queue.
Step 5 : Add to the rear of the Queue all the neighbours of the deleted node that are not visited or added in a Queue.
Step 5 : Exit.
Applications of Graphs:
1. Analysis of Electrical Networks: Graphs, digraphs are used to analyze electrical networks. Electrical circuits can be represented
by graphs.
2. Study of Molecular Structure: The study of molecular structure of chemical compounds requires graphs.
3. Used for representation of Airlines Routes: To represent airline route system airports are considered to be vertices and flights
to be edges and distance or ticket price to be weights.
4. Networks: Computer networks or communication networks can be represented by graphs. Here, vertices are the computers
and edges are communications lines. Weight could be bandwidth.
5. Topological Sort: Graphs are also used to sort elements using the topological sort algorithm.
6. Finding Shortest Paths: Graphs can be used to find shortest path between any two vertices, when it has several routes.
7. Project Management: Graphs are also used to Compute project completion time, delays, early start and late finish times for a
project, which is made up of several tasks.
8. State Transition Diagrams. The nodes represent states, and the edges represent legal moves from state to state. For example,
we could use a graph to represent legal moves in a game of tic-tac-toe.