Unit 4 Graph and Tree Algorithms 1
Unit 4 Graph and Tree Algorithms 1
in
UNIT-4Graph and Tree Algorithms Q1) What are tree and its
terminology?A1)
A Tree is a recursive data structure containing the set of one or more
data nodes where one node is designated as the root of the tree while
the remaining nodes are called as the children of the root.
The nodes other than the root node are partitioned into the non
empty sets where each one of them is to be called sub-tree.
Nodes of a tree either maintain a parent-child relationship between
them or they are sister nodes.
In a general tree, A node can have any number of children nodes but
it can have only a single parent.
The following image shows a tree, where the node A is the root node
of the tree while the other nodes can be seen as the children of A.
Basic terminology
Root Node :- The root node is the topmost node in the tree
hierarchy. In other words, the root node is the one which doesn't have
any parent.
Sub Tree :- If the root node is not null, the tree T1, T2 and T3 is
called sub-trees of the root node.
Leaf Node :- The node of tree, which doesn't have any child node, is
called leaf node. Leaf node is the bottom most node of the tree. There
can be any number of leaf nodes present in a general tree. Leaf nodes
can also be called external nodes.
Path :- The sequence of consecutive edges is called path. In the tree
shown in the above image, path to the node E is A→ B → E.
Ancestor node :- An ancestor of a node is any predecessor node on a
path from root to that node. The root node doesn't have any ancestors.
In the tree shown in the above image, the node F have the ancestors, B
and A.
Degree :- Degree of a node is equal to number of children, a node
have. In the tree shown in the above image, the degree of node B is 2.
Degree of a leaf node is always 0 while in a complete binary tree, degree
of each node is equal to 2.
Level Number :- Each node of the tree is assigned a level number in
such a way that each node is present at one level higher than its parent.
Root node of the tree is always present at level 0.
Static representation of tree
#de ne MAXNODE 500
fi
struct treenode {
int root;
int father;
int son;
int next;
}
Dynamic representation of tree
struct treenode
{
int root;
struct treenode *father;
struct treenode *son
struct treenode *next;
}
Q2) What are the Types of Tree?A2) The tree data structure can be
classi ed into six di erent categories.
fi
ff
General Tree General Tree stores the elements in a hierarchical order
in which the top level element is always present at level 0 as the root
element. All the nodes except the root node are present at number of
levels. The nodes which are present on the same level are called siblings
while the nodes which are present on the di erent levels exhibit the
ff
parent-child relationship among them. A node may contain any
number of sub-trees. The tree in which each node contain 3 sub-tree, is
called ternary tree. Forests Forest can be de ned as the set of disjoint
fi
trees which can be obtained by deleting the root node and the edges
which connects root node to the rst level node.
fi
Binary Tree Binary tree is a data structure in which each node can have
at most 2 children. The node present at the top most level is called the
root node. A node with the 0 children is called leaf node. Binary Trees
are used in the applications like expression evaluation and many more.
We will discuss binary tree in detail, later in this tutorial. Binary Search
Tree Binary search tree is an ordered binary tree. All the elements in the
left sub-tree are less than the root while elements present in the right
sub-tree are greater than or equal to the root node element. Binary
search trees are used in most of the applications of computer science
are used to evaluate the simple arithmetic expressions. Expression tree
is basically a binary tree where internal nodes are represented by
operators while the leaf nodes are represented by operands. Expression
trees are widely used to solve algebraic expressions like (a+b)*(a-b).
Consider the following example. Q3) Construct an expression tree by
using the following algebraic expression. A3) (a + b) / (a*b - c) + d
fi
order tree and right sub-tree respectively. This procedure will
Traversal be applied to each sub-tree of the tree recursively.
Traverse the left sub-tree rst, and then traverse the
In-order
fi
2 root and the right sub-tree respectively. This procedure
Traversal
will be applied to each sub-tree of the tree recursively.
Post- Traverse the left sub-tree and then traverse the right
3 order sub-tree and root respectively. This procedure will be
Traversal applied to each sub-tree of the tree recursively.
Q5) Explain Binary Tree representation A5) There are two types of
representation of a binary tree:1. Linked RepresentationIn this
representation, the binary tree is stored in the memory, in the form of a
linked list where the number of nodes are stored at non-contiguous
memory locations and linked together by inheriting parent child
relationship like a tree. every node contains three parts : pointer to the
left node, data element and pointer to the right node. Each binary tree
has a root pointer which points to the root node of the binary tree. In an
empty binary tree, the root pointer will point to null.Consider the
binary tree given in the gure below.
fi
In the above gure, a tree is seen as the collection of nodes where each
fi
node contains three parts : left pointer, data element and right pointer.
Left pointer stores the address of the left child while the right pointer
stores the address of the right child. The leaf node contains null in its
left and right pointers.The following image shows about how the
memory will be allocated for the binary tree by using linked
representation. There is a special pointer maintained in the memory
which points to the root node of the tree. Every node in the tree
contains the address of its left and right child. Leaf node contains null
in its left and right pointers.
2. Sequential Representation This is the simplest memory allocation
technique to store the tree elements but it is an ine cient technique
ffi
since it requires a lot of space to store the tree elements. A binary tree is
shown in the following gure along with its memory allocation.
fi
In this representation, an array is used to store the tree elements. Size
of the array will be equal to the number of nodes present in the tree.
The root node of the tree will be present at the 1st index of the array. If
a node is stored at ith index then its left and right children will be
stored at 2i and 2i+1 location. If the 1st index of the array i.e. tree[1] is 0,
it means that the tree is empty. Q6) Write a program for expression
treeA6)
#include<bits/stdc++.h>
struct et
{
char value;
};
// is an operator
bool isOperator(char c)
if (c == '+' || c == '-' ||
c == '*' || c == '/' ||
c == '^')
return true;
return false;
if(t)
inorder(t->left);
inorder(t->right);
et* newNode(char v)
{
temp->left = temp->right = NULL;
temp->value = v;
return temp;
};
// post x expression
fi
et* constructTree(char post x[])
fi
{
// input expression
if (!isOperator(post x[i]))
fi
{
t = newNode(post x[i]);
fi
st.push(t);
else // operator
t = newNode(post x[i]);
fi
// Pop two top nodes
t->right = t1;
t->left = t2;
st.push(t);
// tree
t = st.top();
st.pop();
return t;
int main()
return 0;
fi
Due to high precision and robust implementation, BFS is used in
multiple real-life solutions like P2P networks, Web Crawlers, and
Network Broadcasting.
Q9) Explain DFS Algorithm.A9) Depth rst search (DFS) algorithm
fi
starts with the initial node of the graph G, and then goes to deeper and
deeper until we nd the goal node or the node which has no children.
fi
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.Algorithm
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: Push the starting node A on the stack and set its STATUS = 2
(waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3
(processed state)
Step 5: Push on the stack all the neighbours of N that are in the ready
state (whose STATUS = 1) and set their
STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT
Example :Consider the graph G along with its adjacency list, given in
the gure below. Calculate the order to print all the nodes of the graph
fi
starting from node H, by using depth rst search (DFS) algorithm.
fi
Solution :Push H onto the stack
STACK : H
POP the top element of the stack i.e. H, print it and push all the
neighbours of H onto the stack that are is ready state.
Print H
STACK : A
Pop the top element of the stack i.e. A, print it and push all the
neighbours of A onto the stack that are in ready state.
Print A
Stack : B, D
Pop the top element of the stack i.e. D, print it and push all the
neighbours of D onto the stack that are in ready state.
Print D
Stack : B, F
Pop the top element of the stack i.e. F, print it and push all the
neighbours of F onto the stack that are in ready state.
Print F
Stack : B
Pop the top of the stack i.e. B and push all the neighbours
Print B
Stack : C
Pop the top of the stack i.e. C and push all the neighbours.
Print C
Stack : E, G
Pop the top of the stack i.e. G and push all its neighbours.
Print G
Stack : E
Pop the top of the stack i.e. E and push all its neighbours.
Print E
Hence, the stack now becomes empty and all the nodes of the graph
have been traversed.The printing sequence of the graph will be :
H→A→D→F→B→C→G→E
Q10) Di erence between BFS and DFS Binary TreeA10)
ff
BFS DFS
BFS nds the shortest path to the DFS goes to the bottom of a
fi
destination. subtree, then backtracks.
The full form of BFS is Breadth-First The full form of DFS is Depth
Search. First Search.
It uses a queue to keep track of the next It uses a stack to keep track
location to visit. of the next location to visit.
DFS traverses according to
BFS traverses according to tree level.
tree depth.
It is implemented using LIFO
It is implemented using FIFO list.
list.
It requires more memory as compare to It requires less memory as
DFS. compare to BFS.
This algorithm doesn't
This algorithm gives the shallowest path
guarantee the shallowest
solution.
path solution.
There is a need of
There is no need of backtracking in BFS.
backtracking in DFS.
You can never be trapped into nite You can be trapped into
fi
loops. in nite loops.
fi
If you do not nd any goal, you may need If you do not nd any goal,
fi
fi
to expand many nodes before the solution the leaf node backtracking
is found. may occur.
Q11) Explain Bellman Ford AlgorithmA11) This algorithm solves the
single source shortest path problem of a directed graph G = (V, E) in
which the edge weights may be negative. Moreover, this algorithm can
be applied to nd the shortest path, if there does not exist any negative
fi
weighted cycle.Algorithm: Bellman-Ford-Algorithm (G, w, s) for each
vertex v Є G.V v.d := ∞ v.∏ := NIL s.d := 0 for i = 1 to |G.V| - 1 for each
edge (u, v) Є G.E if v.d > u.d + w(u, v) v.d := u.d +w(u, v) v.∏ := u for each
edge (u, v) Є G.E if v.d > u.d + w(u, v) return FALSE return
TRUEAnalysisThe rst for loop is used for initialization, which runs in
fi
O(V) times. The next for loop runs |V - 1| passes over the edges, which
takes O(E) times.Hence, Bellman-Ford algorithm runs in O(V, E)
time.ExampleThe following example shows how Bellman-Ford
algorithm works step by step. This graph has a negative edge but does
th ti l h th bl b l d i thi
technique.At the time of initialization, all the vertices except the source
are marked by ∞ and the source is marked by 0.
In the rst step, all the vertices which are reachable from the source are
fi
updated by minimum cost. Hence, vertices a and h are updated.
Following the same logic, in this step vertices b, f, c and g are updated.