DAA Module-2
DAA Module-2
PART A
3 Organise Order, pre order, post order traversal of the following tree
Algorithm
Step 2 Enqueue the starting node A and set its STATUS = 2 (waiting state)
Step 5 Enqueue 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
Step 2 -Now, delete node A from queue1 and add it into queue2. Insert all
neighbours of node A to queue1.
Step 3 - Now, delete node B from queue1 and add it into queue2. Insert all
neighbours of node B to queue1.
Step 4 - Now, delete node D from queue1 and add it into queue2. Insert all
neighbours of node D to queue1. The only neighbour of Node D is F since it is
already inserted, so it will not be inserted again.
Step 5 - Delete node C from queue1 and add it into queue2. Insert all
neighbours of node C to queue1.
Step 6 - Delete node F from queue1 and add it into queue2. Insert all
neighbours of node F to queue1. Since all the neighbours of node F are already
present, we will not insert them again.
Step 7 - Delete node E from queue1. Since all of its neighbours have already
been added, we will not insert them again. Now, all the nodes are visited, and
the target node E is encountered into queue2.
Depth first search DFS algorithm starts with the initial node of the graph G,
and then goes 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.
Algorithm
Example :
Consider the graph G along with its adjacency list, given in the figure below.
Calculate the order to print all the nodes of the graph starting from node H, by
using depth first search DFS algorithm.
Solution :
POP the top element of the stack i.e. H, print it and push all the neighbours of H
onto the stack that are in ready state.
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.
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.
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.
Pop the top of the stack i.e. B and push all the neighbours
Pop the top of the stack i.e. C and push all the neighbours.
Pop the top of the stack i.e. G and push all its neighbours.
Pop the top of the stack i.e. E and push all its neighbours.
Unlike linear data structures Array, Linked List, Queues, Stacks, etc) which
have only one logical way to traverse them, trees can be traversed in different
ways. Following are the generally used ways for traversing trees.
1 DFS
2 BFS
In DFS, we have:
(a) Inorder Left, Root, Right)
(b) Preorder Root, Left, Right)
(c) Postorder Left, Right, Root)
Inorder Traversal:
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Uses of Inorder: In the case of binary search trees BST , Inorder traversal
gives nodes in non-decreasing order.
Preorder Traversal
Algorithm Preorder(tree)
Uses of Preorder
Preorder traversal is used to create a copy of the tree. Preorder traversal is also
used to get prefix expressions on an expression tree. Preorder traversal for the
above-given figure is 1 2 4 5 3.
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
4 Compare the approaches of BFS and DFS methods and derive the time
complexity of both methods for the inputs of adjacency list and adjacency
matrix separately.
SPANNING TREE
A spanning tree is a subset of Graph G, which has all the vertices covered with
a minimum possible number of edges. Hence, a spanning tree does not have
cycles and it cannot be disconnected..
We now understand that one graph can have more than one spanning tree.
Following are a few properties of the spanning tree connected to graph G −
Spanning tree is basically used to find a minimum path to connect all nodes in a
graph. Common application of spanning trees are −
6 Explain weighting rule for finding UNION of sets and collapsing rule
If the number of nodes in the tree with root i is less than the number in the tree
with the root j, then make ‘j’ the parent of i; otherwise make ‘i’ the parent of j. To
implement the weighting rule we need to know how many nodes are there in
every tree. To do this we maintain a “count” field in the root of every tree. If ‘i’ is
the root then count[i] equals the number of nodes in the tree with roots ‘i’.
Since all nodes other than roots have positive numbers in parent P field, we
can maintain count in P field of the root as negative number.
Algorithm WeightedUnion(i,j)
//Union sets with roots i and j, i j using the weighted rule
//P[i]=-count[i] andp[j]=-count[j]
{
temp:=P[i]+P[j];
if (P[i]>P[j])then {
// i has fewer nodes P[i]:=j;
P[j]:=temp;
}
else {
// j has fewer nodes P[j]:=i;
}
}
Inorder sequence: D B E A F C
Preorder sequence: A B D E C F
We recursively follow the above steps and get the following tree.
(not much info here, better to go check out youtube)
5.7 Construct Binary Tree from Preorder and Inorder traversal with examp…
11 Develop a program to print all the nodes reachable from a given starting
node in a bigraph using the BFS method.
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val)
printInorder(root.right)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.val)
def printPreorder(root):
if root:
print(root.val)
printPreorder(root.left)
printPreorder(root.right)
# Driver code
root = Node("A")
root.left = Node("B")
root.right = Node("C")
root.left.right = Node("D")
root.right.left = Node("E")
root.right.left.left = Node("G")
root.right.right = Node("F")
root.right.right.left = Node("H")
root.right.right.right = Node("I")
If, having found the root, we replace the parent pointer of the given node with a
pointer to the root, the next time we do a Find it will be more efficient. In fact,
we can go one step further and replace the parent pointer of every node along
the search path to the root. This is called a collapsing find operation.
Effect of a collapsing find operation. After the find, all the nodes along the
search path are attached directly to the root. I.e., they have had their depths
decreased to one. As a side-effect, any node which is in the subtree of a node
along the search path may have its depth decreased by the collapsing find
operation. The depth of a node is never increased by the find operation.
Eventually, if we do enough collapsing find operations, it is possible to obtain a
tree of height one in which all the non-root nodes point directly at the root.
15 Construct a binary tree from the following Inorder sequence: 4, 8, 2, 5, 1,
6, 3, 7 and Postorder sequence: 8, 4, 5, 2, 6, 7, 3, 1.
Inorder sequence: 4, 8, 2, 5, 1, 6, 3, 7
Postorder sequence: 8, 4, 5, 2, 6, 7, 3, 1
16 Explain step count method and analyse the time complexity when two
nxn matrices are added.
The step count method is one of the methods to analyse the algorithm. In this
method, we count the number of times one instruction is executing. From that
we will try to find the complexity of the algorithm.
Given below is the step count table of general matrix addition algorithm:
Here, the number of rows and columns are equal to n. Therefore, the total time
complexity for matrix addition is as follows:
Time Complexity: n2
18 What is meant by divide and conquer? Give the recurrence relation for
divide and conquer.
If the sizes of the two subproblems are approximately equal then the
computing time of DANDC is given by the recurrence relation:
DANDC (P) {
if SMALL (P) then return S (p);
else {
divide p into smaller instances p1, p2, .... Pk, k>=1;
apply DANDC to each of these sub problems;
return (COMBINE (DANDC (p1) , DANDC (p2),...., DANDC (pk)); }
}
If the sizes of the two subproblems are approximately equal then the
computing time of DANDC is given by the recurrence relation:
20 Find out any two drawbacks of the binary search algorithm.
Binary search is an efficient algorithm for finding an item from a sorted list of
items. It works by repeatedly dividing in half the portion of the list that could
contain the item, until you’ve narrowed down the possible locations to just one.
The drawbacks of Binary Search algorithm are as follows:
● It employs a recursive approach which requires more stack space.
● Programming binary search algorithms is error prone and difficult.
● The interaction of binary search with memory hierarchy i.e. caching is
poor. (because of its random access nature)