Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

COPYRIGHT © 2021 AKU BTECH BIHAR All rights reserved. visit: https://www.akubtechbihar.

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

Tournament Tree Tournament tree are used to record the winner of


the match in each round being played between two players.
Tournament tree can also be called as selection tree or winner tree.
External nodes represent the players among which a match is being
played while the internal nodes represent the winner of the match
played. At the top most level, the winner of the tournament is present
as the root node of the tree. For example, tree .of a chess tournament
being played among 4 players is shown as follows. However, the winner
in the left sub-tree will play against the winner of right sub-tree.

Q4) Explain Binary TreeA4) Binary Tree is a special type of generic


tree in which, each node can have at most two children. Binary tree is
generally partitioned into three disjoint subsets.
Root of the node
left sub-tree which is also a binary tree.
Right binary sub-tree
A binary Tree is shown in the following image.
Types of Binary Tree1. Strictly Binary TreeIn Strictly Binary Tree, every
non-leaf node contain non-empty left and right sub-trees. In other
words, the degree of every non-leaf node will always be 2. A strictly
binary tree with n leaves, will have (2n - 1) nodes.A strictly binary tree
is shown in the following gure.
fi
2. Complete Binary Tree A Binary Tree is said to be a complete binary
tree if all of the leaves are located at the same level d. A complete binary
tree is a binary tree that contains exactly 2^l nodes at each level
between level 0 and d. The total number of nodes in a complete binary
tree with depth d is 2d+1-1 where leaf nodes are 2d while non-leaf
nodes are 2d-1.

Binary Tree Traversal


1 Pre- Traverse the root rst then traverse into the left sub-

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>

using namespace std;

// An expression tree node

struct et

{
char value;

et* left, *right;

};

// A utility function to check if 'c'

// is an operator

bool isOperator(char c)

if (c == '+' || c == '-' ||

c == '*' || c == '/' ||

c == '^')

return true;

return false;

// Utility function to do inorder traversal

void inorder(et *t)

if(t)

inorder(t->left);

printf("%c ", t->value);

inorder(t->right);

// A utility function to create a new node

et* newNode(char v)

{
temp->left = temp->right = NULL;

temp->value = v;

return temp;

};

// Returns root of constructed tree for given

// post x expression
fi
et* constructTree(char post x[])
fi
{

stack<et *> st;

et *t, *t1, *t2;

// Traverse through every character of

// input expression

for (int i=0; i<strlen(post x); i++)


fi
{

// If operand, simply push into stack

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

t1 = st.top(); // Store top

st.pop(); // Remove top


st.pop();

// make them children

t->right = t1;

t->left = t2;

// Add this subexpression to stack

st.push(t);

// only element will be root of expression

// tree

t = st.top();

st.pop();

return t;

// Driver program to test above

int main()

char post x[] = "ab+ef*g*-";


fi
et* r = constructTree(post x);
fi
printf("in x expression is \n");
fi
inorder(r);

return 0;

Output in x expression is a + b - e * f * g Q7) What are the Rules and


fi
application of BFS Algorithm?A7) Here, are important rules for using
A queue (FIFO-First in First Out) data structure is used by BFS.
You mark any node in the graph as root and start traversing the data
from it.
BFS traverses all the nodes in the graph and keeps dropping them as
completed.
BFS visits an adjacent unvisited node, marks it as done, and inserts it
into a queue.
Removes the previous vertex from the queue in case no adjacent
vertex is found.
BFS algorithm iterates until all the vertices in the graph are
successfully traversed and marked as completed.
There are no loops caused by BFS during the traversing of data from
any node.
Applications of BFS AlgorithmLet's take a look at some of the real-life
applications where a BFS algorithm implementation can be highly
e ective.
ff
Un-weighted Graphs: BFS algorithm can easily create the shortest
path and a minimum spanning tree to visit all the vertices 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 nd the required
fi
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 nd all the neighbouring
fi
locations from the main or source location.
Network Broadcasting: A broadcasted packet is guided by the BFS
algorithm to nd and reach all the nodes it has the address for.
fi
Q8) Give a small brief on BFS algorithmA8)
A graph traversal is a unique process that requires the algorithm to
visit, check, and/or updates every single un-visited node in a tree-like
structure. BFS algorithm works on a similar principle.
The algorithm is useful for analyzing the nodes in a graph and
constructing the shortest path of traversing through these.
The algorithm traverses the graph in the smallest number of
iterations and the shortest possible time.
BFS selects a single node (initial or source point) in a graph and then
visits all the nodes adjacent to the selected node. BFS accesses these
nodes one by one.
The visited and marked data is placed in a queue by BFS. A queue
works on a rst in rst out basis. Hence, the element placed in the
fi
fi
graph rst is deleted rst and printed as a result.
fi
fi
The BFS algorithm can never get caught in an in nite loop.

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.

In the next step, vertices a, b, f and e are updated.

Following the same logic, in this step vertices b, f, c and g are updated.

Here, vertices c and d are updated.


Hence, the minimum distance between vertex s and vertex d is
20.Based on the predecessor information, the path is s→ h→ e→ g→ c→
d

Viewed using Just Read

You might also like