0% found this document useful (0 votes)
44 views

Data Structures Module 4 QB Complete Solutions

The document contains 15 questions related to graphs and trees. It includes questions about depth first search and breadth first search algorithms on graphs represented using adjacency matrices. It also includes questions about binary tree traversals like preorder, inorder and postorder, constructing binary search trees from given data, deleting entire binary trees, and printing the left view of a binary tree.

Uploaded by

22951a67h8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Data Structures Module 4 QB Complete Solutions

The document contains 15 questions related to graphs and trees. It includes questions about depth first search and breadth first search algorithms on graphs represented using adjacency matrices. It also includes questions about binary tree traversals like preorder, inorder and postorder, constructing binary search trees from given data, deleting entire binary trees, and printing the left view of a binary tree.

Uploaded by

22951a67h8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

MODULE 4

PART A

1. Let G be a graph with n vertices and m edges. Find the tightest


upper bound on the running time on depth first search of graph G.
Assume that the graph is represented using an adjacency matrix.

A. Depth First Search of a graph takes O(m+n) time when the graph
is represented using an adjacency list. In adjacency matrix
representation, the graph is represented as an ‘n x n’ matrix. To do
DFS, for every vertex, we traverse the row corresponding to that
vertex to find all adjacent vertices (In adjacency list representation
we traverse only the adjacent vertices of the vertex). Therefore
time complexity becomes O(n2).

2. Let G be an undirected graph with n vertices and 25 edges such


that each vertex has degree at least 3. Find the maximum
possible value of n?

A. As per handshaking lemma,


Sum of degree of all vertices < = 2 * no. of edges.
Let v be the number of vertices in the graph.
==> 3 * v <= 2 * 25
==> Maximum value of v = 16
3. In a binary tree, for every node the difference between the
number of nodes in the left and right subtrees is at most 2. If the
height of the tree is h > 0, then the minimum number of nodes in
the tree is:

A. 2h-1 + 1
Let there be n(h) nodes at height h.
In a perfect tree where every node has exactly
two children, except leaves, following recurrence holds.
n(h) = 2n(h-1) + 1
In given case, the numbers of nodes are two less, therefore
n(h) = 2n(h-1) + 1 - 2
= 2n(h-1) - 1
The above equation is only satisfied by 2h-1 + 1

4. Write a program to find the number of occurrences of a number


in a tree of numbers?

A. A tree of numbers is stored as an array in any programming


language. Number of occurrences of a number can be counted
using a simple count increment program.

5. Write breadth first search (BFS) traversal algorithm, based on a


queue, to traverse a directed graph of n vertices and m edges?

Refer to the image in this link for better understanding.


6. Consider the example. Find BFS and DFS.

A.

7. Draw a directed graph with five vertices and seven edges.


Exactly one of the edges should be a loop, and do not have any
multiple edges.

A.
8. Given A Binary Tree. Write an efficient algorithm to delete the
entire binary tree.

A. To delete a tree, we must traverse all the nodes of the tree and
delete them one by one. We should use the postorder transversal
because before deleting the parent node, we should delete its child
nodes first.
Algorithm Postorder Tree Deletion:
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root and delete the node

9. Given A Binary Tree. Write an efficient algorithm to print a left


view of a binary tree.

A. This is solved by recursively traversing each level in the


tree(visiting the left node before the right node). Whenever we
move to the next level, print the leftmost node in that level (Note:
we traverse the left subtree before the right subtree). The variable
maxlevel is used to track the maximum level in the tree that is
traversed so far. Each time a node with a level greater than maxlevel
is encountered, its value is printed, ​and the value of maxlevel is
updated to that value.

class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None

# Recursive function to print left view of a binary tree.


# It takes a root, the current level, and
# the max level so far of the binary tree
def leftViewUtil(root, level, max_level):
if root is None:
return

if (max_level[0] < level):


print(root.data)
max_level[0] = level

leftViewUtil(root.left, level + 1, max_level)


leftViewUtil(root.right, level + 1, max_level)

def leftView(root):
max_level = [0]
leftViewUtil(root, 1, max_level)

10. Given a binary tree, write a recursive solution to traverse the


tree using post order traversal.
A.

# Data structure to store a binary tree node


class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
# Recursive function to perform postorder traversal on
tree
def postorder(root):
# return if the current node is empty
if root is None:
return
# Traverse the left subtree
postorder(root.left)
# Traverse the right subtree
postorder(root.right)
# Display the data part of the root (or current node)
print(root.data, end=' ')
PART B

1. Construct a Binary Search Tree for the following data and do


in-order, Preorder and Postorder traversal of the tree.
50, 60, 25, 40, 30, 70, 35, 10, 55, 65, 5
Preorder, Inorder and Postorder in 5 minute | Tree Traversal | E…

2. Explain the breadth first search and depth first search tree
traversal on the following graph.
A.
Reference:
5.1 Graph Traversals - BFS & DFS -Breadth First Search and De…

3. Question Incomplete

4. Develop a program in Python to implement Depth First Search


traversal of a graph using Adjacency Matrix.

class Graph:
adj = []
# Function to fill empty adjacency matrix
def __init__(self, v, e):
self.v = v
self.e = e
Graph.adj = [[0 for i in range(v)]
for j in range(v)]

# Function to add an edge to the graph


def addEdge(self, start, e):
# Considering a bidirectional edge
Graph.adj[start][e] = 1
Graph.adj[e][start] = 1
# Function to perform DFS on the graph
def DFS(self, start, visited):
# Print current node
print(start, end = ' ')
# Set current node as visited
visited[start] = True
# For every node of the graph
for i in range(self.v):
# If some node is adjacent to the
# current node and it has not
# already been visited
if (Graph.adj[start][i] == 1 and
(not visited[i])):
self.DFS(i, visited)
# Driver code
v, e = 5, 4
# Create the graph
G = Graph(v, e)
G.addEdge(0, 1)
G.addEdge(0, 2)
G.addEdge(0, 3)
G.addEdge(0, 4)
visited = [False] * v
# Perform DFS
G.DFS(0, visited);

LINK:
https://www.geeksforgeeks.org/implementation-of-dfs-using-adjac
ency-matrix/

5. Construct a binary search tree by inserting the following nodes


in sequence: 68, 85, 23, 38, 44, 80, 30, 108, 26, 5, 92, 60. Write
in-order, pre-order and post-order traversal of the above
generated Binary search tree.
Follow same procedure as 1st Question
6. Write the in-order, pre-order and post-order traversals for the
given binary tree.

Follow same procedure as 1st Question

7. Define Adjacency Matrix? Draw the Adjacency Matrix of the


following graph. Also give adjacency list representation for the
same.

A. Adjacency Matrix:
● Adjacency Matrix is a 2D array of size V x V where V is the
number of vertices in a graph.
● Let the 2D array be adj[ ][ ], a slot adj[i][j] = 1 indicates that
there is an edge from vertex i to vertex j.
● Adjacency matrix for an undirected graph is always symmetric.
Adjacency Matrix is also used to represent weighted graphs. If
adj[i][j] = w, then there is an edge from vertex i to vertex j with
weight w.

8. Explain the array and linked representation of a binary tree


using a suitable example?
A. LINK : Data Structures Tutorials - Binary Tree Representations
with an example

9. Define a binary tree? Construct a binary tree given the


pre-order traversal and in-order traversals as follows:
Pre-Order Traversal: G B Q A C K F P D E R H
In-Order Traversal: Q B K C F A G P E D H R
A. A binary tree is a tree data structure in which each node has at
most two children, which are referred to as the left child and the
right child.
5.7 Construct Binary Tree from Preorder and Inorder traversal …

10. Construct an expression tree for the following expression. A +


( B + C* D + E ) + F / G. Make a preorder traversal of the resultant
tree.
A.

PRE ORDER: +A+++*CDBE/FG (DOUBT)


11. Explain the binary tree traversal algorithms with a suitable
example?

A. Pre order (VLR):


In this traversal method, the root node is visited first, then the left
subtree and finally the right subtree. Give any example
Inorder (LVR):
In this traversal method, the left subtree is visited first, then the
root and later the right subtree. We should always remember that
every node may represent a subtree itself.
If a binary tree is traversed in-order, the output will produce sorted
key values in an ascending order. Give any example.
Post Order (LRV):
In this traversal method, the root node is visited last, hence the
name. First we traverse the left subtree, then the right subtree and
finally the root node. Give any example.

12. Write the basic tree terminologies and the properties of binary
trees?
13. Explain the breadth first search and depth first search graph
traversal algorithms for the following graph?

BFS : A B C E G F D H
DFS: A B C D E H G F

14. Explain the following with an example: i. Full binary tree ii.
Strictly binary tree iii. Complete binary tree
● If every non leaf node in a binary tree has nonempty left and
right subtrees, the tree is called a strictly binary tree.
● A strictly binary tree with n leaves always contains 2n -1
nodes.

15. Write the applications of trees and graphs?


A. Graphs
● In Data Structures, graphs are used to represent the flow of
computation.
● Google maps uses graphs for building navigation systems,
where intersection of two(or more) roads are considered to be
a vertex and the road connecting two vertices is considered to
be an edge, thus their navigation system is based on the
algorithm to calculate the shortest path between two vertices.
Trees
● 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. For example, a binary tree
has a logN time for searching an element.
● Heap: It is also a tree data structure implemented using arrays.
It is used to implement priority queues.

16. The Breadth First Search algorithm has been implemented


using the queue data structure. Discover breadth first search for
the graph shown in Figure with starting node M.

A.
BFS: M R Q N P O

17. Define a binary search tree and write the properties of a binary
search tree? Construct a binary search with the following keys:
8, 3, 1, 6, 14, 4, 7, 13, 17, 5
18. Write the procedure for finding an element 85 in a given binary
search tree?

A.
● The element to be searched is 85.
● Compare 85 with the root node.
● Since 85>33 we can move to the right subtree.
● Compare 85 with 60. Since 85> 60 we can move to the right
subtree. Since 85<90 we can move to the left subtree.
● Since 85<86 we can move to the left subtree.
● 85> 81 but 81 has no children hence 85 is not present in the
binary tree.

19. Write a program for Breadth First Search traversal of a graph?


from collections import defaultdict
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, s):
# Mark all the vertices as not visited
visited = [False] * (max(self.graph) + 1)
# Create a queue for BFS
queue = []
# Mark the source node as
# visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
# Dequeue a vertex from
s = queue.pop(0)
print (s, end = " ")
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent
# has not been visited, then mark it
# visited and enqueue it
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
# Driver code
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
g.BFS(2)

LINK:
https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-g
raph/

20. Write the in-order, pre-order and post-order traversal of a


given tree?

A.
PART C

1.Write the children for node ‘w’ of a complete-binary tree in an


array representation?
Ans. 2w and 2w+1

2. Write the advantages of linked list representation of binary


trees over arrays?
Ans. It has both dynamic size and ease in insertion and deletion as
advantages.
3. Write the different tree traversal algorithms in linked list
representation?
Ans. Inorder Traversal
Inorder Traversal is the one the most used variant of DFS(Depth
First Search) Traversal of the tree. As DFS suggests, we will first
focus on the depth of the chosen Node and then go to the breadth
at that level. Therefore, we will start from the root node of the tree
and go deeper-and-deeper into the left subtree in a recursive
manner. When we reach the left-most node with the above steps,
then we will visit that current node and go to the left-most node of
its right subtree (if it exists). Same steps should be followed in a
recursive manner to complete the inorder traversal. Order of those
steps will be like (in recursive function).
1. Go to left-subtree
2. Visit Node
3. Go to right-subtree

Preorder Traversal
Preorder Traversal is another variant of DFS. Where atomic
operations in a recursive function, are as same as Inorder traversal
but with a different order.
Here, we visit the current node first and then goes to the left
sub-tree. After covering every node of the left sub-tree, we will
move towards the right subtree and visit in a similar fashion.
Order of the steps will be like…
1. Visit Node
2. Go to left-subtree
3. Go to right-subtree

Postorder Traversal
Where we visit the left subtree and the right subtree before visiting
the current node in recursion.
So, the sequence of the steps will be
1. Go to left-subtree
2. Go to right-subtree
3. Visit Node

4. State the graph traversal technique which is similar to level


order tree traversal?
Ans. Breadth First Search (BFS) algorithm is similar to level order
tree traversal traverses a graph in a breadthward motion and uses a
queue to remember to get the next vertex to start a search, when a
dead end occurs in any iteration.

Figure
As in the example given above, the BFS algorithm traverses from A
to B to E to F first then to C and G lastly to D. It employs the
following rules.
● Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited.
Display it. Insert it in a queue.
● Rule 2 − If no adjacent vertex is found, remove the first vertex
from the queue.
● Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.

5. Write the recursive algorithm for pre-order traversal?


Ans.

class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
# Recursive function to perform preorder traversal on
tree
def preorder(root):

# return if the current node is empty


if root is None:
return

# Display the data part of the root (or current node)


print(root.data, end=' ')

# Traverse the left subtree


preorder(root.left)

# Traverse the right subtree


preorder(root.right)
6. Write the name of the tree traversal technique which would
print the numbers in an ascending order in binary search tree?
Ans. Inorder traversal of BST prints it in ascending order.

7.Define a full binary tree and complete binary tree?


Ans. A full binary tree can be defined as a binary tree in which all
the nodes have 0 or two children. In other words, the full binary tree
can be defined as a binary tree in which all the nodes have two
children except the leaf nodes.

A binary tree is said to be a complete binary tree when all the levels
are completely filled except the last level, which is filled from the
left.

8. Write the time complexity for finding the height of the binary
tree?
Ans. O(n). A breadth first search from the root is probably the
fastest way to do this. You only need to visit each node once, and,
owing to the simple structure of a binary tree, you never have to
keep track of visited nodes or anything like that. You don't have to
even track the “deepest node seen so far” because you do an entire
tier at a time with BFS.

9. Write the worst case and average case complexities of a binary


search tree?
Ans. Binary search’s average and worst case time complexity is
O(logn), while binary search tree does have an average case of
O(logn), it has a worst case of O(n). Namely when the tree’s height
equals the number of items in the tree (incredibly unlikely in any real
scenario).

10. Write the number of edges present in a complete graph having


n vertices?
Ans. The number of edges present in a complete graph having n
vertices is (n*(n-1))/2

11. Write the different ways used to represent a graph in a


computer?
Ans. In graph theory, a graph representation is a technique to store
graphs into the memory of a computer. There are different ways to
optimally represent a graph:
Adjacency Matrix:
Adjacency matrix is a sequential representation. It is used to
represent which nodes are adjacent to each other. i.e is there any
edge connecting nodes to a graph. In this representation, we have
to construct a nXn matrix A. If there is any edge from a vertex i to
vertex j, then the corresponding element of A, ai,j = 1, otherwise
ai,j= 0. If there is any weighted graph then instead of 1s and 0s, we
can store the weight of the edge.
Example
Consider the following undirected graph representation:
Undirected graph representation

Directed graph representation


See the directed graph representation:
In the above examples, 1 represents an edge from row vertex to
column vertex, and 0 represents no edge from row vertex to column
vertex.
Undirected weighted graph representation

Incidence Matrix:
In Incidence matrix representation, graph can be represented using
a matrix of size:
Total number of vertices by total number of edges. It means if a
graph has 4 vertices and 6 edges, then it can be represented using
a matrix of 4X6 class. In this matrix, columns represent edges and
rows represent vertices. This matrix is filled with either 0 or 1 or -1.
Where,
● 0 is used to represent the row edge which is not connected to
the column vertex.
● 1 is used to represent the row edge which is connected as the
outgoing edge to the column vertex.
● -1 is used to represent the row edge which is connected as
incoming edge to column vertex.
Example
Consider the following directed graph representation.
Adjacency List:
Adjacency list is a linked representation.
In this representation, for each vertex in the graph, we maintain the
list of its neighbours. It means, every vertex of the graph contains a
list of its adjacent vertices .We have an array of vertices which is
indexed by the vertex number and for each vertex v, the
corresponding array element points to a singly linked list of
neighbours of v.
Example
Let's see the following directed graph representation implemented
using linked list:

We can also implement this representation using array as follows:


12. Write the DFS traversal of the given graph?

Ans. DFS - ABCDE

13. Write the maximum number of edges present in a simple


directed graph with 7 vertices if there exists no cycles in the
graph?
A. For n vertices, there exists (n-1) edges. Therefore, the maximum
number of edges is 6.

14. State the difference between pre-order traversal and


postorder traversal?
Ans. In order to illustrate few of the binary tree traversals, let us
consider the below binary tree:
Pre-order traversal: To traverse a binary tree in Pre-order, following
operations are carried-out
(i) Visit the root,
(ii) Traverse the left subtree, and
(iii) Traverse the right subtree.
Therefore, the Pre-order traversal of the above tree will outputs:
7, 1, 0, 3, 2, 5, 4, 6, 9, 8, 10
Post-order traversal: To traverse a binary tree in Post-order,
following operations are carried-out
(i) Traverse all the left external nodes starting with the left most
subtree which is then followed by bubble-up all the internal nodes,
(ii) Traverse the right subtree starting at the left external node
which is then followed by bubble-up all the internal nodes, and
(iii) Visit the root.
Therefore, the Postorder traversal of the above tree will outputs:
0, 2, 4, 6, 5, 3, 1, 8, 10, 9, 7

15. Write the applications of trees?


Ans. The applications of trees are:
● One reason to use trees might be because you want to store
information that naturally forms a hierarchy.
● If we organize keys in the form of a tree (with some ordering
e.g., BST), we can search for a given key in moderate time
(quicker than Linked List and slower than arrays).
Self-balancing search trees like AVL and Red-Black trees
guarantee an upper bound of O(Logn) for search.
● We can insert/delete keys in moderate time (quicker than
Arrays and slower than Unordered Linked Lists).
Self-balancing search trees like AVL and Red-Black trees
guarantee an upper bound of O(Logn) for insertion/deletion.
● Like Linked Lists and unlike Arrays, Pointer implementations of
trees don’t have an upper limit on number of nodes as nodes
are linked using pointers.
● Manipulate hierarchical data.
● Make information easy to search (see tree traversal).
● Manipulate sorted lists of data

16. Define binary search tree and its operations?


Ans. A Binary Search Tree (BST) is a tree in which all the nodes
follow the below-mentioned properties −
● The value of the key of the left sub-tree is less than the value
of its parent (root) node's key.
● The value of the key of the right subtree is greater than or
equal to the value of its parent (root) node's key.
Thus, BST divides all its sub-trees into two segments; the left
subtree and the right subtree and can be defined as −
left_subtree (keys) < node (key) ≤ right_subtree (keys)
BST is a collection of nodes arranged in a way where they maintain
BST properties. Each node has a key and an associated value. While
searching, the desired key is compared to the keys in BST and if
found, the associated value is retrieved.
Following is a pictorial representation of BST –

Basic Operations
Following are the basic operations of a tree −
• Search − Searches an element in a tree.
• Insert − Inserts an element in a tree.
• Pre-order Traversal − Traverses a tree in a pre-order manner.
• In-order Traversal − Traverses a tree in an in-order manner.
• Post-order Traversal − Traverses a tree in a post-order
manner.

17. Define a strictly binary tree with an example?


Ans.
If every non leaf node in a binary tree has nonempty left and right
subtrees, the tree is called a strictly binary tree.
A strictly binary tree with n leaves always contains 2n -1 nodes.
If every non-leaf node in a binary tree has nonempty left and right
subtrees, the tree is termed a strictly binary tree. Or, to put it
another way, all of the nodes in a strictly binary tree are of degree
zero or two, never degree one.

18. Write any two applications of priority queue?


Ans. Applications of Priority queue
The following are the applications of the priority queue:
o It is used in Dijkstra's shortest path algorithm.
o It is used in prim's algorithm
o It is used in data compression techniques like Huffman code.
o It is used in heap sort.
o It is also used in operating systems like priority scheduling,
load balancing and interrupt handling.

19. Write the advantages of priority queue?


Ans. A Priority Queue is different from a normal queue, because
instead of being a “first-in-first-out”, values come out in order by
priority. It is an abstract data type that captures the idea of a
container whose elements have “priorities” attached to them. The
advantages of priority queue are that:
• Easy to implement
• Processes with different priority can be efficiently handled
• Applications with differing requirements

20. Write the time complexity to insert a node based on position


in a priority queue?
Ans. O(n)

You might also like